简体   繁体   English

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

[英]Can it be done in a more elegant way with the Swing Timer?

Bellow is the code for the simplest GUI countdown. Bellow是最简单的GUI倒计时的代码。 Can the same be done in a shorter and more elegant way with the usage of the Swing timer? 使用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();
            }
        });
    }

}

Yes you SHOULD use a Swing Timer. 是的你应该使用Swing Timer。 You SHOULD NOT, use a util Timer and TimerTask. 你不应该使用util Timer和TimerTask。

When a Swing Timer fires the code is executed on the EDT which means you just need to invoke the label.setText() method. 当Swing Timer触发时,代码在EDT上执行,这意味着您只需要调用label.setText()方法。

When using the uitl Timer and TimerTask, the code DOES NOT execute on the EDT, which means you need to wrap your code in a SwingUtilities.invokeLater to make sure the code executes on the EDT. 使用uitl Timer和TimerTask时,代码不能在EDT上执行,这意味着您需要将代码包装在SwingUtilities.invokeLater中以确保代码在EDT上执行。

And that is way using a Swing Timer is shorter and more elegant than your current approach, it simplifies the coding because to code is executed on the EDT. 这就是使用Swing Timer比现有方法更短更优雅的方式,它简化了编码,因为代码在EDT上执行。

使用带有适当TimerTask的 Timer可以使它更优雅一些。

Yes, use a timer. 是的,使用计时器。 updateGUI would be the code for the timer task, but it will need some changes as you won't be able to pass in i for each call since you just get a run() method. updateGUI将是计时器任务的代码,但它需要一些更改,因为你只能得到一个run()方法,因为你无法为每次调用传入i。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM