0

I am not sure if I asked right in title but here is the problem. I have a class that does a jop asyncronously and also has to run on Swing UI thread. like this


SwingUtilities.invokeLater(() -> {
  myobj.dosomething(()->{

   SwingUtilities.invokeLater(() -> {
     myobj.dosomething(()->{
       //here it needs to repeat this again and again. 
       //for an indefinte number of times. So it is hedious to reapat this code
       //for few times  and impossible to make it dynamic based on user input. 
       //it was even worse without lambda sytax.
     });
    });
   });
});

Edit:I probably shouldn't have mentioned swing at all. Because it is not the problem it only adds to it. The main problem is that I need to call myobj.dosomething(()->{ too many times. And every time it should start after the previous call is done.

lazyCoding
  • 481
  • 2
  • 5
  • 13
  • You should use javax.swing.Timer – ControlAltDel Sep 23 '19 at 20:32
  • Possible duplicate of [How can I pause/sleep/wait in a java swing app?](https://stackoverflow.com/questions/54865088/how-can-i-pause-sleep-wait-in-a-java-swing-app) – George Z. Sep 23 '19 at 20:37
  • I dont see how Timer is revelant to this problem. Read comented in code please. I need to invoke ```myobj.dosomething ``` ,say, 10 times. each invoke should happen after previous one is done. – lazyCoding Sep 24 '19 at 08:56

1 Answers1

0

If you don't want to use swing timers then create a thread and post your UI code back to the UI thread like this:

Runnable r = new Runnable() {

    public void run() {

         while (condition holds) {
            //sleep, do work, etc.

            //Post UI code back to the Swing thread
            SwingUtilities.invokeLater(() -> { //some ui code }
         }
    }
};

Thread t = new Thread(r);
t.start();
Locutus
  • 444
  • 4
  • 12