我正在用 Java Swing 编写我的第一个复杂应用程序。当我将 ActionListener 添加到我的 JButton 时。
ActionListener changeButton = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e){
if(startButton.getText() == "Spustit") {
startButton.setText("STOP");
} else {
startButton.setText("Spustit");
}
}
}
我将 ActionListener 添加到按钮本身
private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {
startButton.addActionListener(changeButton);
}
你能告诉我 ActionListener 的编码哪里不好吗?
谢谢大家!
最佳答案
您已经对 ActionListener 进行了足够好的编码,至少可以为操作监听器本身工作。问题是您在事件(您的第二个示例)之后添加操作监听器,因此您的操作监听器将在您第二次单击它时被调用。
解决方案非常简单:
JButton button = new JButton();
button.addActionListener( new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//...
}
});
现在,如果您直接向按钮添加新的 ActionListener,则操作监听器应在第一次单击时激活,而不是在执行操作后激活
关于java - java中的ActionListener在第二次单击时执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26424841/