如何每帧多次重绘 JFrame 及其组件?

How can I redraw a JFrame and its components multiple times per frame?

我正在尝试在用户单击按钮时更新 JLabel,就像这样的伪代码:

private static void ButtonAction()
{
    // Set label to `loading..`

    // Perform action

    // Set label to `ready.`
}

我尝试使用:

frame.invalidate();
frame.validate();
frame.repaint();

到目前为止运气不好。或者我的按钮动作太快,看不到它的切换?

如何确保用户同时看到 loading..ready

Or maybe my button action is too fast to see it switching?

如果是,那么除非您想设置一个计时器来显示最终值,否则您无能为力。

How can I make sure that the user sees both loading.. and ready?

更常见的情况是,当您执行较长的 运行 任务时,您需要使用 Threads,这样您就不会阻止框架响应事件并重新绘制自身。

阅读 Concurrency 上的 Swing 教程部分了解更多信息。也许你可以使用 SwingWorker。

如果您不使用 SwingWorker,则需要创建自己的线程,然后在需要更新标签时使用 SwingUtilities.invokeLater(...)。