呼叫
counter.start()
在可运行文件中:
// The main method (entry point).
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
showGUI();
counter.start();
}
});
}
您真的想要一个特定的调用顺序,如果您将它放在线程之外,那么计数器将在GUI存在之前启动,并且它将在您身上失败。
对于第二个问题:
// A method which updates GUI (sets a new value of JLabel).
private static void updateGUI(final int i, final JLabel label) {
SwingUtilities.invokeLater(new Worker(i, label));
}
这是工人:
import javax.swing.JLabel;
public class Worker implements Runnable{
private int i;
private JLabel label;
public Worker(int i, JLabel label) {
this.i = i;
this.label = label;
}
public void run() {
label.setText("You have " + i + " seconds.");
}
}
现在你的主要任务是:
// The main method (entry point).
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
Countdown.showGUI();
counter.start();
}
});
}
更新:
或者如果您仍然想使用匿名模式,那么:
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class Countdown {
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.");
}
}
);
}
}