且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

GUI 添加了组件但显示时显示空白

更新时间:2021-11-07 09:06:37

您的 JButton 的 actionPerformed() 代码在 Java 事件调度线程 (EDT) 上执行,这这就是 GUI冻结"并且您看到黑屏的原因.
这样做还会阻止关闭"事件以及任何其他摆动事件的执行.
重要提示:
EDT 是一个特殊的线程,应该非常小心地处理.
请花点时间阅读 EDT 以及如何正确使用它此处.

Your JButton's actionPerformed() code gets executed on the Java event dispatch thread (EDT) and this is why the GUI "freezes" and you see a black screen.
Doing so, also blocks the "close" event from being executed as well as any other swing event.
Important:
The EDT is a special thread which should be handled very carefully.
Please take the time and read on EDT and how to properly use it here.

正确方法:
doTimer() 应该永远在 Java 事件调度线程 (EDT) 上运行,因为它模拟(我希望)一些长时间运行的任务.
为了确保我们正确处理 EDT,我们使用 SwingWorker.
SwingWorkers 是一种特殊结构,旨在在后台线程中执行冗长的 GUI 交互任务.
由于这是第一次处理有点棘手,我为您添加了以下代码:

Correct method:
doTimer() should never run on Java event dispatch thread (EDT) since it simulates (I hope) some long-running task.
To make sure we handle the EDT correctly we use a SwingWorker.
SwingWorkers are special constructs designed to perform lengthy GUI-interaction tasks in a background thread.
Since this is kinda tricky to handle for the first time, I added the following code for you:

@Override
public void actionPerformed(ActionEvent e) {
    SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() {
        @Override
        protected Object doInBackground() throws Exception {
            // Code here will be executed in a background thread
            // This is where all background activities should happen.
            doTimer();
            return null;
        }
    };
    sw.execute();
    //  doTimer(); Bad Idea as this will execute on EDT!
}