How to combine Swing and SpringFramework?
Asked Answered
H

1

6

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?

Headliner answered 4/3, 2015 at 10:16 Comment(1)
Try #22864508Jonathanjonathon
I
1

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
  }
});
Intercross answered 4/3, 2015 at 10:38 Comment(2)
not this is not good idea, EDT waitng until whatever from ClassPathXmlApplicationContext is loaded, invokeLater is designated to notify methods implemented in Swing APIs, methods in those APIs,Caption
That may be a shortcut yes and not an ultimate solution.Intercross

© 2022 - 2024 — McMap. All rights reserved.