一个动作监听器,两个JButtons

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

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

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

 JButton leftButton, rightButton; public void actionPerformed(ActionEvent e) { Object src = e.getSource(); if (src == leftButton) { } else if (src == rightButton) { } }