Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine Swing and SpringFramework?

Swing requires to run from within Event Dispatch Thread (EDT). How to ensure this in Spring context?

In some tutorials, like this one, swing components are just instantiated like normal beans. Is this ok?

like image 604
Suzan Cioc Avatar asked Mar 04 '15 10:03

Suzan Cioc


1 Answers

As you have already guessed, it would be safer to run your Swing code within the Event Dispatching Thread aka EDT because most of the Swing components are not thread safe. Here is what stated in Oracle docs:

Swing event handling code runs on a special thread known as the event dispatch thread. Most code that invokes Swing methods also runs on this thread. This is necessary because most Swing object methods are not "thread safe": invoking them from multiple threads risks thread interference or memory consistency errors.

So you should be safe to go if your initialiaze your Spring ApplicationContext whithin the EDT thread so that your components get initialized and run in the same thread:

SwingUtilities.invokeLater(new Runnable() 
{
  public void run() 
  {
    new ClassPathXmlApplicationContext( "your-application-context.xml" ); // pay attention to context so that it is not left open
  }
});
like image 194
tmarwen Avatar answered Nov 02 '22 06:11

tmarwen