Java 在按钮中使用计时器

Java Util Timer in a Button

我正在做一个棋盘游戏,在游戏的一部分中,我需要有这样的按钮,当它被点击时,会以 1 秒的延迟间隔重复更改标签,从 1 到 5,然后会将标签更改为 "done",但问题是它先将标签更改为 "done",然后再计数。

btn.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent arg0) {
            timer = new Timer();
            timer.scheduleAtFixedRate(new TimerTask() {
                // @Override
                public void run() {
                    count++;
                    if (count >= 6) {
                        timer.cancel();
                        timer.purge();
                        return;
                    }
                    lbl.setText(String.valueOf(count));
                }
            }, 1000,1000);
            lbl.setText("done");
        }});

当你点击按钮时,actionPerformed()方法被顺序执行:

  1. 创建新计时器
  2. 注册一个每秒定时执行的任务,以后
  3. 将按钮标签设置为"Done"

然后,稍后,计时器完成它的工作,将开始增加变量计数,每次更新按钮标签。像这样阅读应该有助于您理解发生了什么:计时器在单独的线程中执行。 timer.scheduleAtFixedRate()是一个非阻塞函数,注册一个TimerTask稍后执行,returns立即

要解决您的问题,类似的解决方案可能是:

btn.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent arg0) {
            timer = new Timer();
            timer.scheduleAtFixedRate(new TimerTask() {
                // @Override
                public void run() {
                    count++;
                    if (count >= 6) {
                        timer.cancel();
                        timer.purge();

                        // We set the label to done only when the counter
                        // reaches the value 6, after button displayed 5
                        lbl.setText("done");

                        return;
                    }
                    lbl.setText(String.valueOf(count));
                }
            }, 1000,1000);
        }});