【问题标题】:Updating a JFrame更新 JFrame
【发布时间】:2012-08-20 06:15:00
【问题描述】:

我有一个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!");
}

【问题讨论】:

    标签: java swing jlabel countdowntimer


    【解决方案1】:

    您需要使用javax.swing.Timer 对您的应用程序进行计时。

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

    如果您想了解其工作原理的示例,可以查看以下答案:https://stackoverflow.com/a/1006640/1515592

    【讨论】:

      【解决方案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();
      

      【讨论】:

      • 谢谢。我有一些更好的代码,但仍然无法让它工作。我将您的答案标记为解决方案。由于我的代码现在完全不同,我将重新发布而不是污染这个线程。再次感谢!
      猜你喜欢
      • 2013-03-29
      • 1970-01-01
      • 1970-01-01
      • 2023-01-11
      • 2011-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多