在程序终止时打印按钮点击次数

Printing # of button clicks at termination of program

我有三个标记为 A、B 和 C 的 JButton。10 秒后程序退出,总点击次数打印到控制台。我是一个完全的新手,在点击打印时遇到了问题。结果总是 0。我需要每个按钮的点击次数来计入总数。看来我还没有完全掌握变量的本质,所以我希望有人把它推到我面前,这样我就可以学习它了,拜托。

a.addActionListener(new ActionListener() {
     int _clicks;
     public void actionPerformed(ActionEvent eco){
         _clicks++;
     }
 });
b.addActionListener(new ActionListener() {
     int _clicks;
     public void actionPerformed(ActionEvent eco){
         _clicks++;
     }
 });
c.addActionListener(new ActionListener() {
     int _clicks;
     public void actionPerformed(ActionEvent eco){
         _clicks++;
     }
 });

int delay = 10000;
 ActionListener taskPerformer = new ActionListener() {
     int _clicks;

     public void actionPerformed(ActionEvent evt) {
         System.out.println("You clicked "+_clicks+" times! Woop");
         System.exit(0);    
    }
   };
   new Timer(delay, taskPerformer).start();

您需要在外部 class 中创建 click 的实例字段,所有 _clicks 变量仅在它们所在的 ActionListener 中具有上下文创建,这意味着它们的值不会在 ActionListener 的实例之外共享,其中定义了

查看 Understanding Class Members 了解更多详情

public class MyAwesomeClass extends ... {
    private int clickCount;

    //...

    a.addActionListener(new ActionListener() {
        //int _clicks;
        public void actionPerformed(ActionEvent eco){
            clickCount++;
        }
    });

    //...

    int delay = 10000;
    ActionListener taskPerformer = new ActionListener() {
        //int _clicks;

        public void actionPerformed(ActionEvent evt) {
            System.out.println("You clicked "+clickCount+" times! Woop");
            // It might be nicer to close the active window
            System.exit(0);    
        }
    };

新定时器(延迟, taskPerformer).start();