invokeLater
部分不太理解。据我了解,
invokeLater
会将任务发送给事件调度线程(EDT),然后EDT会在“可以”时执行此任务。这是正确的吗?据我理解,代码的工作方式如下:
1.在
main
方法中,我们使用invokeLater
显示窗口(showGUI
方法)。换句话说,显示窗口的代码将在EDT中执行。2.在
main
方法中,我们还启动了counter
,而且该计数器(按构造)在另一个线程中执行(因此不在事件调度线程中)。对吗?3.
counter
在单独的线程中执行,定期调用updateGUI
。 updateGUI
应该更新GUI。 而GUI在EDT中工作。 因此,updateGUI
也应在EDT中执行。 这就是为什么updateGUI
的代码被包含在invokeLater
中的原因。这是正确的吗?不清楚的是为什么要从EDT调用
counter
。无论如何,它不在EDT中执行。它会立即启动一个新线程,并在那里执行counter
。 所以,为什么我们不能在invokeLater
块之后的主方法中调用counter
呢?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();
}
});
}
}