我的代码遇到问题。我想知道是否有一种更简单的方法来使用监听器,而不是不断地这样做:
example.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
if (example.isSelected()) {
System.out.println("Example is selected");
所以我对每个单选按钮都这样做,这意味着我必须一遍又一遍地重复相同的代码。现在可能很简单,但假设我使用了 100 多个单选按钮。然后我就不得不一遍又一遍地重复它。有没有更简单的方法来做到这一点?
这是我正在使用的代码,您可以在那里找到其中的一些代码:
最佳答案
您可以在使用 ActionListener 之前定义它,这样您就可以这样做:
ActionListener myListener = new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
if (evt.getSource() == radioButton1) {
...
} else if (evt.getSource() == radioButton2) {
...
}
}
然后在任何你想要的地方使用它:
radioButton1.addActionListener(myListener);
radioButton2.addActionListener(myListener);
关于Java 监听器 - 更简单的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23020529/