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

查看:18
本文介绍了可以使用 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 的方式比您当前的方法更短、更优雅,它简化了编码,因为代码是在 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 以更优雅的方式完成吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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