将代码延迟给定秒



这是一个使用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;
}

您正在阻塞事件调度线程(不,也不要使用thread.sleep())。使用摆动计时器:

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

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

使用javax.swing.TimersetRepeats设置为false

最新更新