【问题标题】:countdown timer minutes and seconds problems Java倒数计时器分秒问题Java
【发布时间】:2016-05-08 11:03:01
【问题描述】:

首先,这不是一个重复的问题。我只是在倒数计时器和其他东西上遇到了麻烦。每当我运行代码时,它只是静止不动,并没有按计划进行。

这是代码。我在构造函数中这样做。我哪里做错了?提前致谢。

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;

public static int counterSeconds = 0; 
public static int counterMinutes = 10; 
public static Timer timer; 

public Quiz1Start() {
    do {
        Quiz1Start.timer = new Timer(1000, new ActionListener() { 
            public void actionPerformed(ActionEvent e) {
                if(Quiz1Start.counterSeconds == 0) {
                    Quiz1Start.counterSeconds = 60;
                    Quiz1Start.counterSeconds--; 
                    Quiz1Start.counterMinutes--;

                    Quiz1Start.jLabelMinute.setText(String.valueOf(counterMinutes)); 
                    Quiz1Start.jLabelSeconds.setText(String.valueOf(counterSeconds));                         
                } else if(Quiz1Start.counterMinutes == 0) {
                    Quiz1Start.timer.stop(); 
                }
            }
        });
        timer.start();
    } while(counterMinutes == 0);
}

【问题讨论】:

  • 我尝试将它放在 if-else 之外并且在声明 ActionListener 之前,这两个都不起作用。 ._.
  • 有很多事情对我提出了疑问。为什么要在构造函数中循环?例如,为什么不在start 方法中。第二。对于每个循环/循环,您构建一个新的计时器,每个计时器都有自己的值等。您期望会发生什么?为什么要检查 Timer Listener 和 while 循环中是否通过了分钟?尝试将所有代码放在一个方法中,然后从构造函数中单独调用它。除了删除while循环,因为它在这里没有用。

标签: java user-interface netbeans-8


【解决方案1】:

检查这部分 - while(counterMinutes==0);

您定义了|counterMinutes|如10。第一轮后循环不会继续。

应该是这样的

do {
...
} while(counterMinutes!=0)

【讨论】:

  • 谢谢你的想法,先生,但它没有奏效。我想在actionPerformed中还有一些东西需要配置...
【解决方案2】:

好的,感谢用户 n247s 和 Uğur B 分享他的想法,现在我明白了,我将声明移到另一个新方法中,然后我将代码更改为 if-else 之外,它工作了! :D

【讨论】:

  • 更不用说我也删除了do-while,我认为重复倒计时需要它,尤其是几分钟..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-12
相关资源
最近更新 更多