5

I have two JButtons called "Left" and "Right". The "Left" button moves a rectangle object to the left and the "Right" button moves it to the right. I have one ActionListener in the class that acts as the listener for when either button is clicked. However I want different actions to happen when each are clicked. How can I distinguish, in the ActionListener, between which was clicked?

Jack
  • 131,802
  • 30
  • 241
  • 343
CodyBugstein
  • 21,984
  • 61
  • 207
  • 363
  • 2
    possible duplicate of [Java - Handle multiple events with one function?](http://stackoverflow.com/questions/501533/java-handle-multiple-events-with-one-function) – Andrew Thompson Jan 21 '13 at 16:45

2 Answers2

8

Set actionCommand to each of the button.

// Set the action commands to both the buttons.

 btnOne.setActionCommand("1");
 btnTwo.setActionCommand("2");

public void actionPerformed(ActionEvent e) {
 int action = Integer.parseInt(e.getActionCommand());

 switch(action) {
 case 1:
         //doSomething
         break;
 case 2: 
         // doSomething;
         break;
 }
}

UPDATE:

public class JBtnExample {
    public static void main(String[] args) {
        JButton btnOne = new JButton();
        JButton btnTwo = new JButton();

        ActionClass actionEvent = new ActionClass();

        btnOne.addActionListener(actionEvent);
                btnTwo.addActionListener(actionEvent);

        btnOne.setActionCommand("1");
        btnTwo.setActionCommand("2");
    }
} 

class ActionClass implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        int action = Integer.parseInt(e.getActionCommand());
        switch (action) {
        case 1:
            // DOSomething
            break;
        case 2:
            // DOSomething
            break;                          
        default:
            break;
        }
    }
}
Wojciech Wirzbicki
  • 3,887
  • 6
  • 36
  • 59
Amarnath
  • 8,736
  • 10
  • 54
  • 81
  • I think this one is more elegant in general. Thanks! – CodyBugstein Jan 21 '13 at 16:56
  • Just a second though, does this require that the ActionListener be in the same class? – CodyBugstein Jan 21 '13 at 16:59
  • 1
    Define one ActionListener class. Declare an object of the action class in the UI class. Set each button actionListener using addActionListener method and add this action class reference as param and finally set action command to each of them. – Amarnath Jan 21 '13 at 17:02
6

Quite easy with the getSource() method available to ActionEvent:

JButton leftButton, rightButton;

public void actionPerformed(ActionEvent e) {
  Object src = e.getSource();

  if (src == leftButton) {

  }
  else if (src == rightButton) {

  }
}
Jack
  • 131,802
  • 30
  • 241
  • 343