你如何在 Java 中将 ActionListener 添加到 JButton 上 [英] How do you add an ActionListener onto a JButton in Java
问题描述
private JButton jBtnDrawCircle = new JButton("Circle");
private JButton jBtnDrawSquare = new JButton("Square");
private JButton jBtnDrawTriangle = new JButton("Triangle");
private JButton jBtnSelection = new JButton("Selection");
如何向这些按钮添加动作侦听器,以便从主方法中我可以对它们调用 actionperformed
,以便在单击它们时我可以在我的程序中调用它们?
How do I add action listeners to these buttons, so that from a main method I can call actionperformed
on them, so when they are clicked I can call them in my program?
推荐答案
两种方式:
1. 在你的类中实现 ActionListener,然后使用 jBtnSelection.addActionListener(this);
之后,你必须定义一个方法,public voidactionPerformed(ActionEvent e)
.但是,对多个按钮执行此操作可能会令人困惑,因为 actionPerformed
方法必须检查每个事件的源 (e.getSource()
) 以查看它是哪个按钮来自.
1. Implement ActionListener in your class, then use jBtnSelection.addActionListener(this);
Later, you'll have to define a menthod, public void actionPerformed(ActionEvent e)
. However, doing this for multiple buttons can be confusing, because the actionPerformed
method will have to check the source of each event (e.getSource()
) to see which button it came from.
2. 使用匿名内部类:
jBtnSelection.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selectionButtonPressed();
}
} );
稍后,您必须定义selectionButtonPressed()
.当您有多个按钮时,这会更有效,因为您对处理操作的各个方法的调用就在按钮的定义旁边.
Later, you'll have to define selectionButtonPressed()
.
This works better when you have multiple buttons, because your calls to individual methods for handling the actions are right next to the definition of the button.
2,更新.由于 Java 8 引入了 lambda 表达式,您可以说与 #2 基本相同的内容,但使用更少的字符:
2, Updated. Since Java 8 introduced lambda expressions, you can say essentially the same thing as #2 but use fewer characters:
jBtnSelection.addActionListener(e -> selectionButtonPressed());
在这种情况下,e
是 ActionEvent.这是有效的,因为 ActionListener 接口只有一个方法,actionPerformed(ActionEvent e)
.
In this case, e
is the ActionEvent. This works because the ActionListener interface has only one method, actionPerformed(ActionEvent e)
.
第二种方法还允许您直接调用selectionButtonPressed
方法.在这种情况下,如果发生其他一些操作,您也可以调用 selectionButtonPressed()
- 例如,当计时器关闭时或其他情况(但在这种情况下,您的方法将被命名为不同的名称,也许 <代码>selectionChanged()).
The second method also allows you to call the selectionButtonPressed
method directly. In this case, you could call selectionButtonPressed()
if some other action happens, too - like, when a timer goes off or something (but in this case, your method would be named something different, maybe selectionChanged()
).
这篇关于你如何在 Java 中将 ActionListener 添加到 JButton 上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!