如何在线程中更新 JFrame 标签?- 爪哇

2022-01-24 00:00:00 user-interface java jframe

我尝试了很多,但似乎无法让它发挥作用.

I have tried a lot, but can't seem to get it to work.

有人告诉我在以下示例中使用 EDT.

I was told to use EDT with the following example.

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            //  Modify the GUI here
        }
});

我已经阅读了很多关于这个主题的内容,但仍然不明白.我知道线程是什么,但 .invokeLater 对我来说仍然没有意义.老实说,如果您能详细解释这将是一个很大的帮助!

I have read on this topic a lot and still don't understand. I get what a thread is, but the .invokeLater still makes no sense to me. Honestly if you can explain in detail this it would be a big help!

程序目标:获取每秒不断创建的随机生成的密钥,以便随后在 GUI 中自行更新.

Goal of Program: To get the randomly generated key that is constantly created every second to update itself afterward in the GUI.

推荐答案

所以有一个EDT(Event Dispatch Thread).出现在屏幕上的所有操作都由 EDT 执行.每个 Swing 应用程序只有一个 EDT.

So there is an EDT (Event Dispatch Thread). All actions that appear on your screen are executed by the EDT. There is only one EDT per Swing application.

您在某个任意线程中,并且想通过该线程更新 GUI?就像我说的每个摇摆应用程序只有一个 EDT,所以你必须告诉 EDT 显示标签(或任何你想要的上下文).

You are in some arbitrary thread and you want to update the GUI through that thread? Well like I said there is only one EDT for each swing application, so you have to tell that EDT to display the label (or whatever context you want).

这里的想法是将这个 Runnable 推送到 EDT 从中提取的队列中.最终,当所有其他操作完成时,EDT 将处理您的可运行文件.

The idea here, is you push this Runnable onto a queue that the EDT pulls from. Eventually, your runnable will be processed by the EDT when all other actions before it are completed.

相关文章