So I'm doing a basic MVC layout for a pretty basic game that I am making. The game requires the user to move up/down/left/right via buttons on the GUI. Since I'm using an MVC layout and my buttons are in a different class than the ActionListeners, I was wondering what the best way to add the action listeners are?
Method 1:
View Class ActionListener method:
public void addMovementListeners(ActionListener u, ActionListener d, ActionListener l, ActionListener r){
moveUp.addActionListener(u);
moveDown.addActionListener(d);
moveLeft.addActionListener(l);
moveRight.addActionListener(r);
}
Control Class add ActionListener method:
private void addListeners(){
viewGUI.addMovementListeners(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonPressed = 1;
}
},
new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonPressed = 2;
}
},
new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonPressed = 3;
}
},
new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonPressed = 4;
}
});
}
Method 2:
View Class ActionListener method:
public void addMovementListeners(ActionListener a){
moveUp.addActionListener(a);
moveDown.addActionListener(a);
moveLeft.addActionListener(a);
moveRight.addActionListener(a);
}
public JButton[] getButtons(){
JButton[] temp = new JButton[4];
temp[0] = moveUp;
temp[1] = moveDown;
temp[2] = moveLeft;
temp[3] = moveRight;
return temp;
}
Control Class add ActionListener method:
JButton[] movementButtons;
private void addListeners(){
movementButtons = viewGUI.getButtons();
viewGUI.addMovementListeners(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == movementButtons[0]){
buttonPressed = 1;
}else if(e.getSource() == movementButtons[1]){
buttonPressed = 2;
}else if(e.getSource() == movementButtons[2]){
buttonPressed = 3;
}else if(e.getSource() == movementButtons[3]){
buttonPressed = 4;
}
}
});
}
Which method is better? Is there another method that is even better than these two? Let me know! Trying to get this MVC thing down :). (Any other suggestions welcome as well)!