gpt4 book ai didi

java - 可以用 Swing Timer 以更优雅的方式完成吗?

转载 作者:行者123 更新时间:2023-12-01 19:23:55 25 4
gpt4 key购买 nike

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

}

最佳答案

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

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

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

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

关于java - 可以用 Swing Timer 以更优雅的方式完成吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2487349/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com