简体   繁体   中英

Displaying information from multiple threads in a single JFrame

I start several(threads) instances of a java class that receives an "input" and based on that generates an "output" on out it out on the standard output(screen). I would like to add an option that would enable me to send this output to a single JFrame (text area). What is the best way of doing this? Up to this point my program was totally GUIless but I would like to make it a bit more GUI friendly and add this option.

The challenge is that at any given point I could have several threads running. Any design or code snippets would be greatly appreciated.

As MadProgrammer points out, a nice, encapsulated way of doing this is SwingWorker .

That said, here is the general theory:

All updates to Swing components must be done on the Swing event dispatch thread (there are some exceptions, but not relevant here). This is achieved by SwingUtilities.invokeLater() (and occasionally invokeAndWait() ).

The Swing runtime will then queue up the changes you want to make and call them one at a time. This makes the entire problem of updating your text area pretty trivial: just create a Runnable with the text you want to append, pass that to invokeLater() , and have your Runnable grab the document model of the text area and append your desired text to it.

SwingWorker can encapsulate some of the complexities of background thread management, but I encourage you to do it the 'hard way' a time or two (and your use-case is actually easier to do the 'hard way'). That way you can appreciate what SwingWorker does for you when you do need it.

You need not to convert your existing threads to SwingWorker s. Just let them from time to time send messages to JFrame in a way like this:

  EventQueue.invokeLater(new Runnable(){
       // update GUI
  });

To avoid boilerplate code, it is good to wrap programming interface to the screen with a java.lang.reflect.Proxy . An example of such wrapping is at SwingProxyActorTest.java .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM