Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Update JFrame via another Thread

843804Jun 25 2005 — edited Aug 2 2005
Hello,

I have a JFrame with a JProgressBar, and I need to see the JProgressBar fill as some operation executes. In that JFrame there's a public method that increments the JProgressBar. This serves as a GUI to another class. That other class receives, as an argument, the JFrame, in order to be able to call that public method to increment the JProgressBar.

Something like:
public class Worker{

   public Worker(JFrame jf){
      this.frame = jf;
   }

   public doWork(){
      instruction1;
      frame.updateProgressBar();
      instruction2;
      frame.updateProgressBar();
   }
}
This has a major problem: the JFrame's graphics won't be updated (you won't see the progress bar filling during the operation). So I made a class to run the Worker on a Thread, that looks something like:
public class WorkerThread extends Thread{

   public WorkerThread (Worker w){
      this.worker= w;
   }

   public void run(){
      w.doWork();     
   }
}
This got the problem solved, the JProgressBar is now correctly updated. But it created a new problem: I need the JFrame to wait for the WorkerThread to finish, and that's what I'm having real trouble with:
public class GUI extends JFrame{

   private worker = new Worker();

   void someButtonPressed(...){
      WorkerThread wt = new WorkerThread(worker);
      wt.start();

      System.out.println("I don't want to see this until the Thread finishes");
   }
}
If I leave this as is, I'll see the text before the Thread finishes.
So I added "wait()" between the last two instructions, and a "notify()" as the last instruction of the run() method on WorkerThread. Unfortunately, this gives me two exceptions (java.lang.IllegalMonitorStateException: current thread not owner), one when I call wait() and another when I call notify(). If I make the two methods that call wait() and notify() synchronized, the JFrame's graphics won't update correctly (back to the initial problem).

Any suggestions? Sorry for the long post, and thanx in advance! :)
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 30 2005
Added on Jun 25 2005
4 comments
84 views