Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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, the do some processing section does not process until I close the progress bar JFrame.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
112 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...