我有一个JFrame
,我想在上面模拟一个倒数计时(如火箭发射)。因此,我通过隐藏各种控件(setVisible(false)
)并显示带有文本的JLabel
(这是应该倒数的文本:3,2,1,Go)来设置框架。
该JLabel
上的文本以“3”开头。我的目的是简单地让程序执行一秒钟,然后将文本更改为“2”,再等待一秒钟,更改为“1”,依此类推。最后,我隐藏了JLabel
并重新显示了所有控件,一切正常进行。
我在做什么没有用。似乎要等待正确的时间,完成后,我的JFrame看起来很棒并且可以按预期工作。但是在倒计时方法的4秒钟中,我所看到的只是一个白色的JFrame。不是我想要的3、2、1。
这是我的代码。谁能看到我做错了吗?谢谢!
public void countdown() {
long t0, t1;
myTest.hideTestButtons(true);
myTest.repaint();
t0 = System.currentTimeMillis();
do {
t1 = System.currentTimeMillis();
} while ( (t1 - t0) < 1000);
myTest.TwoSeconds();
myTest.repaint();
t0 = System.currentTimeMillis();
do {
t1 = System.currentTimeMillis();
} while ( (t1 - t0) < 1000);
myTest.OneSecond();
myTest.repaint();
t0 = System.currentTimeMillis();
do {
t1 = System.currentTimeMillis();
} while ( (t1 - t0) < 1000);
myTest.Go();
myTest.repaint();
t0 = System.currentTimeMillis();
do {
t1 = System.currentTimeMillis();
} while ( (t1 - t0) < 1000);
myTest.hideTestButtons(false);
myTest.repaint();
}
public void TwoSeconds() {
lblCountdown.setText("2");
}
public void OneSecond() {
lblCountdown.setText("1");
}
public void Go() {
lblCountdown.setText("Go!");
}
最佳答案
请改用Timer
。在大多数情况下,强烈建议不要积极等待。
这是您需要集成的代码类型:
final Timer ti = new Timer(0, null);
ti.addActionListener(new ActionListener() {
int countSeconds = 3;
@Override
public void actionPerformed(ActionEvent e) {
if(countSeconds == 0) {
lblCountdown.setText("Go");
ti.stop();
} else {
lblCountdown.setText(""+countSeconds);
countSeconds--;
}
}
});
ti.setDelay(1000);
ti.start();