如果您在 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);
}
});
}
}