【问题标题】:Delay a code by given seconds将代码延迟给定秒数
【发布时间】:2013-08-28 18:45:01
【问题描述】:

这是一个使用 java 编写的代码,可以将代码的执行延迟 5 秒。但它不起作用。 "this.jLabel2.setText("TDK");"声明不起作用。谁能帮我解决这个问题。

 private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    this.jLabel2.setText("TDK");
    boolean result=false;
    result=stop();
    if(result)
    {
      this.jLabel1.setText("MDK");
    }
}
public boolean stop()
{
    String current= new java.text.SimpleDateFormat("hh:mm"
            + ":ss").format(new java.util.Date(System.currentTimeMillis()));
    String future=new java.text.SimpleDateFormat("hh:mm"
            + ":ss").format(new java.util.Date(System.currentTimeMillis()+5000));   

    while(!(current.equals(future)))
    {
       current= new java.text.SimpleDateFormat("hh:mm"
               + ":ss").format(new java.util.Date(System.currentTimeMillis()));  
    }

      return true;
}

【问题讨论】:

  • 听说过“睡眠”功能吗?执行这样的 while 循环会消耗 CPU 周期。此外,循环运行的速度可能不够快,以至于当前时间实际上等于未来,您必须查看当前时间是否 >= 未来。
  • 注意:你不想在 EDT 中延迟。你会冻结 UI。
  • 我猜你的代码正在运行,你应该在冻结 5 秒后看到“MDK”。还有Spinlocksftw.
  • @zapl 是 MDK 在 5 秒后显示。但是当我按下按钮时没有显示“TDK”。 5 秒后也会显示“TDK”

标签: java delay wait


【解决方案1】:

您正在阻塞事件调度线程(不,也不要使用 Thread.sleep())。使用秋千Timer

Timer timer = new Timer(HIGHLIGHT_TIME, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        jLabel1.setText("MDK");
    }
});
timer.setRepeats(false);
timer.start();

其中HIGHLIGHT_TIME 是您要延迟设置文本的时间。

【讨论】:

    【解决方案2】:

    使用javax.swing.Timer 并将setRepeats 设置为false

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-12
      • 2012-11-14
      • 1970-01-01
      • 2022-01-27
      • 2012-04-20
      • 1970-01-01
      • 1970-01-01
      • 2020-11-13
      相关资源
      最近更新 更多