One action listener, two JButtons

元气小坏坏 提交于 2019-12-03 20:21:22

问题


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?


回答1:


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;
        }
    }
}



回答2:


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) {

  }
}


来源:https://stackoverflow.com/questions/14443259/one-action-listener-two-jbuttons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!