Jamie Keeling Jamie Keeling - 10 days ago 6
Java Question

Java Threads with Swing UI

After having some trouble with setting up a thread to start my MIDI sequencer I decided to simply remove it, although it would slow my UI down I would be able to use it correctly.

What I noticed however was that even when playing the Sequencer the UI was very much active, even if it was playing around 500 notes the UI worked perfectly fine.

Now I know that in C# if you are doing something intensive it is advisable to load it on a new Thread as it will free the UI. Is it the same principle in Java, it's really confused me. If so can someone explain how the UI is not being blocked?

Thanks

Edit:

The following code actually plays the Sequence

public static boolean Play() {
if(!_sequencer.isRunning()) {
try {
_sequencer.setSequence(_sequence);
_sequencer.start();

return true;
} catch (Exception e) {
Logger.Add(e.getMessage());
}
}
return false;
//Already running
}

Answer

Yes, it is the same theory. Only the Event Thread can modify the UI, and thus if you are doing anything on that thread, then you are preventing other events from working on the UI.

It may be easier to think about the Event Thread as a queue:

  1. Show Form
  2. Click Button
  3. Do your work (Action)
  4. Reset focus of Button
  5. Update Progress Bar
  6. Et cetera

If #3 takes long, then it may mean that your form will appear locked up. Obviously it completely depends on your definition of long. In general, it's better to work off of the Event Thread rather than on it.