[英]Java - One ActionListener for multiple JButtons
I'm writing a little Java Application.我正在写一点 Java 应用程序。 I have multiple JButtons.
我有多个 JButton。 The code for each button is exactly the same, thus I want only one ActionListener.
每个按钮的代码完全相同,因此我只需要一个 ActionListener。 But in that ActionListener I need to call "setText()" for the corresponding button, which was clicked.
但是在那个 ActionListener 中,我需要为单击的相应按钮调用“setText()”。 Is that possible?
那可能吗? How would I achieve this?
我将如何实现这一目标?
I tried the following:我尝试了以下方法:
private void btnClicked(java.awt.event.ActionEvent evt) {
(JButton)evt.setText("Hello");
}
But that doesn't work - it says "Cannot find symbol".但这不起作用 - 它说“找不到符号”。
Thanks in advance;)提前致谢;)
(JButton)evt.setText("Hello");
You are not invoking any method on the "evt" object.您没有在“evt”object 上调用任何方法。
You need to invoke the getSource()
method to access the button.您需要调用
getSource()
方法来访问该按钮。
I always like to do it the long way so I don't make mistakes:我总是喜欢做很长的路,所以我不会犯错误:
JButton button = (JButton)evt.getSource();
button.setText( "Hello" );
but the short way would be:但简短的方法是:
((JButton)evt.getSource()).setText("Hello");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.