Thread.sleep 运行 乱序

Thread.sleep running out of order

在我的程序中,我尝试在 label.setText() 调用之间使用 Thread.sleep(3000) 几秒钟后进行 JLabel 更新。

public void actionPerformed(ActionEvent e)
{
    gameUpdate.label.setText("text a");
    try {                   
        Thread.sleep(3000);                 
    } 
    catch (InterruptedException ie) 
    {
        ie.printStackTrace();
    }
    gameUpdate.label.setText("text b");
}

发生的情况是按钮被按下但标签没有更新。然后在 3 秒后标签更新为 "text b"。我不明白为什么会这样。

I can't understand why this would be happening.

您正在从 ActionListener 调用代码,并且此代码在事件调度线程 (EDT) 上执行。

Thread.sleep(...) 导致 EDT 休眠,这意味着 GUI 在完成休眠之前无法重新绘制自身。

您需要使用单独的线程。查看 Concurrency 上的 Swing 教程部分以获取更多信息。您可以在 SwingWorkerpublish 结果可用时使用它们。

或者,另一种选择是使用 Swing Timer 来安排文本的更新。本教程还有一个关于 How to Use Timers.

的部分