2013-08-28 49 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是要延遲設置文本的時間。