2

I'm coding a Java 7 Swing application which calls a non-GUI class to do something in a loop. Unfortunately, I can't interact with the GUI while the loop is running. Is it possible to force the processing of GUI events while in that loop?

I'm searching for something that tells the JVM to process other GUI events like button clicks before continuing with the loop.

Is there something in Java 7 Swing that does what I want or do I really have to mess with multi-threading by myself (I'm not that far yet...)?

Nathan
  • 8,093
  • 8
  • 50
  • 76
wullxz
  • 17,830
  • 8
  • 32
  • 51

2 Answers2

8

No, unlike Qt framework (which is C++ based), Java does not support manually processing and/or dispatching UI events (at least, at time of writting, 2022).

In other words, don't block the EDT (Event Dispatch Thread) - the GUI will 'freeze' when that happens (and there is not way out yet). Instead of calling Thread.sleep(n) implement:

  • a Swing Timer for repeating tasks
  • or a SwingWorker for long running tasks.

See Concurrency in Swing for more details.

Top-Master
  • 7,611
  • 5
  • 39
  • 71
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    +1... @wullxz see also [this](http://stackoverflow.com/questions/12641887/swingworker-in-java/12642215#12642215) example which demonstrates `SwingWorker`. And [this](http://stackoverflow.com/questions/14074329/using-sleep-for-a-single-thread/14074427#14074427) which goes further into Andrews comment on `Thread.sleep(..)` – David Kroukamp Jun 30 '13 at 14:22
  • 1
    SwingWorker did the trick. But good to know there's also something like the timer. :) – wullxz Jun 30 '13 at 15:25
5

Use a SwingWorker. Basically, all UI event handling is always done on a single specific thread, called the Event Dispatch Thread, and doing anything else in that thread prevents UI events (mouse clicks, keyboard input etc) from being processed and thus makes the UI "hang".

The SwingWorker class was added to the JRE specifically for doing time-consuming tasks "in the background" (not in the UI thread) and allows you to easily do your heavy lifting someplace else, optionally update the UI at intervals (think progress bar), and, again optionally, update the UI once you're done. You do this simply by overriding specific methods (doInBackground() and done()) and you never need to directly deal with threading.

The SwingWorker Javadoc page has everything you need to start using it, including example code.

Nathan
  • 8,093
  • 8
  • 50
  • 76
radai
  • 23,949
  • 10
  • 71
  • 115