一个动作监听器,二Jbutton将(One action listener, two JButton

2019-07-18 12:29发布

我有两个JButtons被称为“左”和“右”。 “左”键移动的矩形对象向左和“右”按钮将其移动到右侧。 我有一个ActionListener在充当听众被点击任一按钮时为班级。 不过,我希望每个被点击时发生不同的动作。 我怎样才能区分,在ActionListener ,被点击之间?

Answer 1:

设置actionCommand到每个按钮。

//设置动作命令这两个按钮。

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

更新:

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


Answer 2:

很容易用getSource()可用方法ActionEvent

JButton leftButton, rightButton;

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

  if (src == leftButton) {

  }
  else if (src == rightButton) {

  }
}


文章来源: One action listener, two JButtons