java 一个动作监听器,两个 JButton
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14443259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
One action listener, two JButtons
提问by CodyBugstein
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?
我有两个JButtons
叫做“左”和“右”。“左”按钮将矩形对象向左移动,“右”按钮将其向右移动。我ActionListener
在类中有一个充当单击任一按钮时的侦听器。但是,我希望在单击每个操作时发生不同的操作。在 中ActionListener
,我如何区分哪些被点击了?
回答by Amarnath
Set actionCommandto each of the button.
将actionCommand设置为每个按钮。
// 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;
}
}
}
回答by Hyman
Quite easy with the getSource()
method available to ActionEvent
:
使用以下getSource()
方法非常简单ActionEvent
:
JButton leftButton, rightButton;
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
if (src == leftButton) {
}
else if (src == rightButton) {
}
}