I\'m trying to figure out what i am doing wrong with action listeners. I\'m following multiple tutorials and yet netbeans and eclipse are giving me errors when im trying to
There are good answers here but let me address the more global point of adding action listener that listens to multiple buttons.
There are two popular approaches.
Using a Common Action Listener
You can get the source of the action in your actionPerformed(ActionEvent e)
implementation:
JButton button1, button2; //your button
@Override
public void actionPerformed(ActionEvent e) {
JButton actionSource = (JButton) e.getSource();
if(actionSource.equals(button1)){
// YOU BUTTON 1 CODE HERE
} else if (actionSource.equals(button2)) {
// YOU BUTTON 2 CODE HERE
}
}
Using ActionCommand
With this approach you setting the actionCommand
field of your button which later will allow you to use switch
:
button1.setActionCommand("actionName1");
button2.setActionCommand("actionName2");
And later:
@Override
public void actionPerformed(ActionEvent e) {
String actionCommand = ((JButton) e.getSource()).getActionCommand();
switch (actionCommand) {
case "actionName1":
// YOU BUTTON 1 CODE HERE
break;
case "actionName2":
// YOU BUTTON 2 CODE HERE
break;
}
}
Check out to learn more about JFrame Buttons, Listeners and Fields.