Java 更新JFrame

Java 更新JFrame,java,swing,jlabel,countdowntimer,Java,Swing,Jlabel,Countdowntimer,我有一个JFrame,我想在上面模拟倒计时(比如火箭发射)。因此,我通过隐藏各种控件(setVisible(false))并显示带有文本的JLabel(这是应该倒计时的文本:3,2,1,Go)来设置框架 JLabel上的文本从“3”开始。我的意图是让程序的执行等待1秒,然后将文本更改为“2”,再等待一秒钟,更改为“1”,等等)。最后,我隐藏了JLabel,并重新显示所有控件,一切正常进行 我正在做的事情不起作用。它似乎在等待正确的时间量,当它完成时,我的JFrame看起来很棒,并按预期工作。但在

我有一个
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!");
}
public void倒计时(){
长t0,t1;
myTest.hideTestButtons(true);
myTest.repaint();
t0=System.currentTimeMillis();
做{
t1=System.currentTimeMillis();
}而((t1-t0)<1000);
myTest.twoses();
myTest.repaint();
t0=System.currentTimeMillis();
做{
t1=System.currentTimeMillis();
}而((t1-t0)<1000);
myTest.1秒();
myTest.repaint();
t0=System.currentTimeMillis();
做{
t1=System.currentTimeMillis();
}而((t1-t0)<1000);
myTest.Go();
myTest.repaint();
t0=System.currentTimeMillis();
做{
t1=System.currentTimeMillis();
}而((t1-t0)<1000);
myTest.hideTestButtons(假);
myTest.repaint();
}
公共无效两秒(){
lblCountdown.setText(“2”);
}
公共无效一秒(){
lblCountdown.setText(“1”);
}
公开作废Go(){
lblCountdown.setText(“开始!”);
}
您需要使用来在应用程序上进行计时

现在发生的情况是,您在一个线程上运行所有内容,因此UI(在单独的线程上运行)没有机会进行更新


如果你想知道这是如何工作的,你可以看看这个答案:

使用
定时器。在大多数情况下,积极等待是非常不鼓励的。
以下是您需要集成的代码类型:

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();

非常感谢。我有一些更好的代码,但仍然无法让它工作。我把你的答案标为解决办法。由于我的代码现在完全不同了,我将重新发布,而不是污染这个线程。再次感谢!