2013-08-28 50 views
0

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

可能的重复http://stackoverflow.com/questions/3342651/how-can-i-delay-a-java-program-for-a-few-seconds –

+0

有没有听说过“睡眠”功能?像这样做一段时间循环会消耗CPU周期。此外,循环可能无法在当前时间足够快以实现平等未来,您必须查看当前时间是否> =未来。 – PherricOxide

+0

注意:你不想延迟EDT ..你会冻结UI。 – mre

回答

3

您正在阻塞事件分派线程(不,不要使用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是要延迟设置文本的时间。