我有JFrame
我要模拟倒计时(如火箭发射)。所以我通过隐藏各种控件(setVisible(false)
)并显示带有文本的JLabel
来设置框架(这是应该倒计时的文本:3,2,1,Go)。
JLabel
上的文字从“3”开始。我的目的是简单地执行程序等待1秒,然后将文本更改为“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!");
}
答案 0 :(得分:3)
您需要使用javax.swing.Timer来为您的应用程序执行时间安排。
正在发生的事情是您在一个线程上运行所有内容 - 因此UI(在单独的线程上运行)没有机会进行更新。
如果您想了解其工作原理的示例,可以查看以下答案:https://stackoverflow.com/a/1006640/1515592
答案 1 :(得分:2)
请改用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();