可以通过Swing Timer以更优雅的方式完成吗?

时间:2010-03-21 14:08:49

标签: java user-interface swing timer

Bellow是最简单的GUI倒计时的代码。使用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();
            }
        });
    }

}

3 个答案:

答案 0 :(得分:4)

是的你应该使用Swing Timer。你不应该使用util Timer和TimerTask。

当Swing Timer触发时,代码在EDT上执行,这意味着你只需要调用label.setText()方法。

使用uitl Timer和TimerTask时,代码不能在EDT上执行,这意味着你需要将代码包装在SwingUtilities.invokeLater中,以确保代码在EDT上执行。

这就是使用Swing Timer比现有方法更短更优雅的方式,它简化了编码,因为代码在EDT上执行。

答案 1 :(得分:0)

Timer与适当的TimerTask结合使用,可以使其更加优雅。

答案 2 :(得分:0)

是的,使用计时器。 updateGUI将是计时器任务的代码,但它需要一些更改,因为你只能获得run()方法,因为你无法为每次调用传入i。