如果你已经在你的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