如果你已經在你的GUI代碼中定義的一些工作,這樣
Runnable doWorkRunnable = new Runnable() {
@Override
public void run() {
doWork();
}
};
,會通過它連接到一個新的Thread
Thread t = new Thread(doWorkRunnable);
t.start();
你執行你在GUI線程工作叫它,這會在Swing應用程序中造成問題。
相反試試這個(讓我提這僅僅是使用的例子)
SwingUtilities.invokeLater(doWorkRunnable);
這使你的Runnable
工人AWT事件隊列,並在以往活動完成後會執行它。
編輯:這是一個完整的例子,它執行從3到0的倒計時,然後在倒計時後做任何你想做的事情。
public class TestFrame extends JFrame {
private JPanel contentPane;
private final Timer timer;
private TimerTask[] tasks;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestFrame frame = new TestFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public TestFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
final JLabel lblCountdown = new JLabel();
contentPane.add(lblCountdown, BorderLayout.NORTH);
JButton btnStart = new JButton("Start");
contentPane.add(btnStart, BorderLayout.SOUTH);
timer = new Timer();
tasks = new TimerTask[4];
setContentPane(contentPane);
for (int i = 0; i < 4; i++) {
final int count = i;
tasks[i] = new TimerTask() {
public void run() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
lblCountdown.setText(count + "");
}
});
}
};
}
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < 4; i++) {
timer.schedule(tasks[4 - i - 1], (1000 * i), (1000 * (i + 1)));
}
// add another timer.schedule(TimerTask)
// to execute that "move to game screen" task
TimerTask taskGotoGame = new TimerTask() {
public void run() {
timer.cancel();
JOptionPane.showMessageDialog(null, "Go to game", "Will now", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
};
// and schedule it to happen after ROUGHLY 3 seconds
timer.schedule(taskGotoGame, 3000);
}
});
}
}
你叫'的Thread.sleep(...)'在事件線程(在美國東部時間)? – 2012-02-29 22:34:22
不,現在不行了。我重寫了以前那樣做的部分代碼。 – scaevity 2012-02-29 22:53:54
@scae您可以分享更新對組件的響應的代碼嗎? – 2012-02-29 23:01:08