Running JFrame with JProgressBar

public void myMethod { MyProgessBarFrame progFrame = new MyProgressBarFrame(); // this is a JFrame progFrame.setVisible(true); // show my JFrame loading // do some processing here while the progress bar is running // ..... progFrame.setvisible(false); // hide my progress bar JFrame } // end method myMethod 

I have the code above. But when I run it, some processing sections are not processed until I close the progress bar of the JFrame.

How will I show my progress bar and tell Java to continue working in the do processing section?

+3
source share
2 answers

You have a classic problem with concurrency and Swing. Your problem is that you are performing a long-term task in the main Swing, EDT or Thread Dispatch Thread, and this will block the thread until the process is complete, preventing it from performing its tasks, including user interaction and drawing a graphical user interface.

The solution is to perform a long-term task in a background thread, such as that specified by a SwingWorker object. You can then update the progress indicator (if qualifier) ​​using the SwingWorker publish / process pair. Read more about this in the Concurrency article in Swing .

eg.

 public void myMethod() { final MyProgessBarFrame progFrame = new MyProgessBarFrame(); new SwingWorker<Void, Void>() { protected Void doInBackground() throws Exception { // do some processing here while the progress bar is running // ..... return null; }; // this is called when the SwingWorker doInBackground finishes protected void done() { progFrame.setVisible(false); // hide my progress bar JFrame }; }.execute(); progFrame.setVisible(true); } 

Also, if this is being displayed from another Swing component, you should probably show a modal JDialog, not a JFrame. This is why I called setVisible (true) in the window after the SwingWorker code, so if this is a modal dialog, it will not interfere with SwingWorker execution.

+9
source

You would notice that when the progress bar is displayed, along with processing the progress bar, the actual task is also executed. Therefore, you can understand that multithreading is happening.

In Java, you can make a separate thread to just show a progress bar, and in the main thread you can complete your task. In this way, both processes will be performed simultaneously, and this will serve your needs.

* NOTE: the progress displayed on the progress bar should depend on the processing performed in the main thread.

You can check these links for Themes and Progress Bar in Java.

+2
source

Source: https://habr.com/ru/post/1394706/


All Articles