2010-03-21 50 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。

相关问题