简体   繁体   English

Swing GUI在数据处理期间不会更新

[英]Swing GUI doesn't update during data processing

I'm having a problem where my Swing GUI components aren't updating for me while the program is busy. 我有一个问题,我的Swing GUI组件在程序繁忙时没有为我更新。 I'm creating an image editor and while heavy processing is happening, I try to change a "status" label while its working to give the user an idea of whats going on. 我正在创建一个图像编辑器,并且在进行繁重的处理时,我尝试更改“状态”标签,同时使用户知道发生了什么。 The label won't update until after the processing is finished though. 标签直到处理完成后才会更新。

How can I update the label IMMEDIATELY instead of having to wait? 如何立即更新标签,而不必等待? My labels are all on a JPanel by the way. 顺便说一下,我的标签都放在了JPanel上。

My label isn't set until after the for loop and the following method finishes. 在for循环和以下方法完成之前,不会设置我的标签。

 labelStatus.setText("Converting RGB data to base 36...");

                            for (int i = 0; i < imageColors.length; i++) {
                                for (int j = 0; j < imageColors[0].length; j++) {
                                    //writer.append(Integer.toString(Math.abs(imageColors[i][j]), 36));
                                    b36Colors[i][j] = (Integer.toString(Math.abs(imageColors[i][j]), 36));
                                }
                            }
                            String[][] compressedColors = buildDictionary(b36Colors);//CORRECTLY COUNTS COLORS

I'm having a problem where my Swing GUI components aren't updating for me while the program is busy. 我有一个问题,我的Swing GUI组件在程序繁忙时没有为我更新。

That is because you are executing a long running task on the Event Dispatch Thread (EDT) and the GUI can't repaint itself until the task finishes executing. 那是因为您正在Event Dispatch Thread (EDT)上执行长时间运行的任务,并且GUI在任务完成执行之前无法重新绘制自身。

You need to execute the long running task in a separate Thread or a SwingWorker (for a better solution). 您需要在单独的线程或SwingWorker中执行长时间运行的任务(以获得更好的解决方案)。 Read the section from the Swing tutorial on Concurrency for more information about the EDT and examples of using a SwingWorker to prevent this problem. 阅读Swing 并发教程中的这一节,以获取有关EDT更多信息以及使用SwingWorker防止此问题的示例。

You can do something like this, not the best but it can give you some idea 你可以做这样的事情,不是最好的,但是它可以给你一些想法

Create a thread dispatcher class and call it from main class 创建一个线程调度程序类,并从主类中调用它

public class ThreadDispatcher implements Runnable { 

public ThreadDispatcher() {

}

public void run() {

        //call the method related heavy process here 

    }     

}  

It may be like this in your main class 在你的主要班级可能就是这样

 Thread thread = new Thread(new ThreadDispatcher());
 thread.start();
 sleep(100);

catch the InterruptedException ex. 赶上InterruptedException ex。

And check the Java thread examples. 并检查Java线程示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM