This discussion is archived
2 Replies Latest reply: Mar 1, 2013 7:41 AM by 978140 RSS

Simple Thread problem

978140 Newbie
Currently Being Moderated
Hi. I have a "static" method that is making some calculations. I would like to have a frame showing up and telling me how much is left of the work. And in the end I would like my static method to return the result. I thought for simplicity that it all would be done in the same static method if possible.

Tried to make the calculation in a separate thread:
public static List calcAndShowProg(){
  MyProgressFrame progressFrame = new MyProgressFrame();

  Runnable runnable = new Runnable() {
   public void run() {
      // Calculations
   }
 };
}
Problem here is that for (1), I dont know how to update the progressFrame from within the thread. Can I get it in there somehow?
And for (2), how would I get the result back to calcAndShowProg()?

Another way of doing it would be to make the progressFrame implements Runnable:
public static List calcAndShowProg(){
   MyProgressFrame progressFrame = new MyProgressFrame();
   new Thread(progressFrame).start();

   // Make the calculations
   while(notFinished){
     progressFrame.updateProgress(..);
   }
Problem here is that progressFrame is showing up but it is blank while my calculations are taking place. Any idea why?
  • 1. Re: Simple Thread problem
    r035198x Pro
    Currently Being Moderated
    You need to use a SwingWorker
  • 2. Re: Simple Thread problem
    978140 Newbie
    Currently Being Moderated
    Thanks. Solved it. But was pretty hard to make SwingWorker for the first time. For others who dont want to spend all day searching:
    public MyClass{
    
       private static List result;
    
      public static List calcAndShowProg(){
        MyProgressFrame progressFrame = new MyProgressFrame();
    
        final GetAndShowProgress work = new GetAndShowProgress(progressFrame);
        work.execute();
    
        progressFrame.showProgress();
        return MyClass.result;
      }
    }
    
    class GetAndShowProgress extends SwingWorker<List<String>,Integer> {
    
      private MyProgressFrame progressFrame;
    
      public GetAndShowProgress(MyProgressFrame progressFrame ){
        this.progressFrame = progressFrame;
      }
    
        @Override
        protected List<String> doInBackground() throws Exception {
           // Calculations
        }
    
        @Override
        public void done() {
          MyClass.result = get();
          progressFrame.dispose();
       }    
    }
    There was also:
    @Override
    protected void process(List<Integer> list)
    To update progress Frame. Thanks again.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points