2010-03-21 49 views
0

貝婁是最簡單的圖形用戶界面倒計時的代碼。使用Swing計時器可以以更短更優雅的方式完成相同的操作嗎?使用擺動計時器可以以更優雅的方式完成嗎?

import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.SwingUtilities; 

public class CountdownNew { 

    static JLabel label; 

    // Method which defines the appearance of the window. 
    public static void showGUI() { 
     JFrame frame = new JFrame("Simple Countdown"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     label = new JLabel("Some Text"); 
     frame.add(label); 
     frame.pack(); 
     frame.setVisible(true); 
    } 

    // Define a new thread in which the countdown is counting down. 
    public static Thread counter = new Thread() { 

     public void run() { 
      for (int i=10; i>0; i=i-1) { 
       updateGUI(i,label); 
       try {Thread.sleep(1000);} catch(InterruptedException e) {}; 
      } 
     } 
    }; 

    // A method which updates GUI (sets a new value of JLabel). 
    private static void updateGUI(final int i, final JLabel label) { 
     SwingUtilities.invokeLater( 
      new Runnable() { 
       public void run() { 
        label.setText("You have " + i + " seconds."); 
       } 
      } 
     ); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       showGUI(); 
       counter.start(); 
      } 
     }); 
    } 

} 

回答

4

是的你應該使用擺動計時器。你不應該使用util Timer和TimerTask。

當Swing Timer觸發時,代碼在EDT上執行,這意味着您只需調用label.setText()方法。

當使用uitl Timer和TimerTask時,代碼不會在EDT上執行,這意味着您需要將代碼包裝在SwingUtilities.invokeLater中以確保代碼在EDT上執行。

這就是使用Swing Timer比使用當前方法更短,更優雅的方法,它簡化了編碼,因爲代碼是在EDT上執行的。

0

是的,使用計時器。 updateGUI將作爲計時器任務的代碼,但它需要一些更改,因爲您只需獲取run()方法就無法爲每次調用傳入i。

相關問題