如何在Java中的JButton上添加ActionListener [英] 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) ;
稍后,你必须定义一个menthod, public void actionPerformed(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.
第二个方法还允许您直接调用选择方法。在这种情况下,你可以调用 selectionButtonPressed()
,如果发生其他一些动作 - 比如,当一个计时器关闭或某事(但在这种情况下,你的方法将是命名不同的东西,可能 selectionChanged()
)。
The second method also allows you to call the selection 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中的JButton上添加ActionListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!