5

我有两个JButtons叫做“左”和“右”。“左”按钮将矩形对象向左移动,“右”按钮将其向右移动。我ActionListener在类中有一个充当单击任一按钮时的侦听器。但是,我希望在单击每个操作时发生不同的操作。我怎样才能区分,在ActionListener哪个被点击?

4

2 回答 2

8

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;
        }
    }
}
于 2013-01-21T16:49:48.297 回答
6

getSource()使用以下方法非常容易ActionEvent

JButton leftButton, rightButton;

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

  if (src == leftButton) {

  }
  else if (src == rightButton) {

  }
}
于 2013-01-21T16:43:31.667 回答