【问题标题】:Can it be done in a more elegant way with the Swing Timer?可以使用 Swing Timer 以更优雅的方式完成吗?
【发布时间】:2011-01-30 01:11:28
【问题描述】:

下面是最简单的 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();
            }
        });
    }

}

【问题讨论】:

    标签: java user-interface swing timer


    【解决方案1】:

    是的,您应该使用摇摆计时器。您不应该使用 util Timer 和 TimerTask。

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

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

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

    【讨论】:

      【解决方案2】:

      您可以通过使用Timer 和适当的TimerTask 使其更优雅。

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 2014-05-15
          • 2015-08-10
          • 1970-01-01
          • 2010-10-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多