Running a JFrame with a JProgressBar

跟風遠走 提交于 2019-11-27 09:21:39

You've got a classic problem with concurrency and Swing. Your problem is that you're doing a long-running task on the main Swing thread, the EDT or Event Dispatch Thread, and this will lock the thread until the process is complete, preventing it from doing its tasks including interacting with the user and drawing GUI graphics.

The solution is to do the long-running task in a background thread such as that given by a SwingWorker object. Then you can update the progressbar (if determinant) via the SwingWorker's publish/process pair. For more on this, please read this article on Concurrency in Swing.

e.g.,

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's 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, then you should probably show a modal JDialog not a JFrame. This is why I called setVisible(true) on the window after the SwingWorker code -- so that if it is a modal dialog, it won't prevent the SwingWorker from being executed.

You would have noticed that when a progress bar is shown, along with processing of the progress bar the actual task is also being done. So you can understand from here that there is multi-threading going on.

In Java you can make a separate thread to just show the progress bar and in main thread you can do your task. So both the processes will run simultaneously and it will serve your need.

*NOTE : the progress shown in progress bar should depend on processing being done in main thread.

you can check these links for Threads & Progress Bar in Java.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!