简体   繁体   中英

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. 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.

My label isn't set until after the for loop and the following method finishes.

 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.

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.

You need to execute the long running task in a separate Thread or a SwingWorker (for a better solution). 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.

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.

And check the Java thread examples.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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