ActionListener问题

Jes*_*ssy 1 java swing

我的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");
   .....
}
Run Code Online (Sandbox Code Playgroud)

Tom*_*ine 5

您可以通过调用来确定调用方法的位置Thread.dumpStack().这会将堆栈跟踪打印到错误流(可能是Java控制台).或者使用调试器并在方法的第一行放置一个断点.

public void actionPerformed(ActionEvent e) {
   Thread.duumpStack();
   System.out.println("This should not appear in the console before button click");
   ...
Run Code Online (Sandbox Code Playgroud)

顺便说一句:我建议不要使用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");
    } 
});
Run Code Online (Sandbox Code Playgroud)

不幸的是,与匿名内部类相关联的样板明显冗长,但意图更清晰.