可以用Swing Timer以更优雅的方式完成吗? [英] Can it be done in a more elegant way with the Swing Timer?

查看:82
本文介绍了可以用Swing Timer以更优雅的方式完成吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Bellow是最简单的GUI倒计时的代码。使用Swing计时器可以以更短更优雅的方式完成吗?

Bellow is the code for the simplest GUI countdown. Can the same be done in a shorter and more elegant way with the usage of the Swing timer?

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();
            }
        });
    }

}


推荐答案

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

Yes you SHOULD use a Swing Timer. You SHOULD NOT, use a util Timer and TimerTask.

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

When a Swing Timer fires the code is executed on the EDT which means you just need to invoke the label.setText() method.

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

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.

使用Swing Timer的方式比现有方法更短更优雅,因为代码执行简化了编码在美国东部时间。

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以更优雅的方式完成吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆