我的 actionListener 有问题。 似乎 actionListener 在我单击按钮之前自动运行? 在我单击按钮之前控制台中出现了“这不应该在按钮单击之前出现在控制台中”……这很奇怪。
....
button1.addActionListener(this);
button2.addActionListener(this);
....
public void actionPerformed(ActionEvent e) {
System.out.println("This should not appear in the console before button click");
if (e.getSource()==button1)
System.out.println ("answer1");
else if (e.getSource()==button2)
System.out.println ("answer2");
.....
}
最佳答案
您可以通过调用 Thread.dumpStack()
知道从哪里调用方法。这会将堆栈跟踪打印到错误流(可能是 Java 控制台)。或者使用调试器并在方法的第一行放置一个断点。
public void actionPerformed(ActionEvent e) {
Thread.duumpStack();
System.out.println("This should not appear in the console before button click");
...
顺便说一句:我建议不要使用 EventObject.getSource
。而是为每个操作添加一个新的监听器。
因此您的示例代码将变为:
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.out.println("answer1");
}
});
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.out.println("answer2");
}
});
不幸的是,与匿名内部类相关的样板文件明显冗长,但意图更清楚。
关于java - ActionListener问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/674883/