一个动作监听器,两个JButtons

问题描述 投票:5回答:2

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

java swing awt jbutton actionlistener
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;
        }
    }
}

6
投票

使用getSource()提供的ActionEvent方法非常简单:

JButton leftButton, rightButton;

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

  if (src == leftButton) {

  }
  else if (src == rightButton) {

  }
}
© www.soinside.com 2019 - 2024. All rights reserved.