Displaying JWindow in the event dispatching thread
-
28-09-2019 - |
Question
What I am trying to do is have a small splash screen appear while my program is loading something. This is what I have:
SplashScreen.showSplashScreen();
// Do stuff that takes time.
SplashScreen.hideSplashScreen();
All the showSplashScreen() method does is create a new JWindow in the middle of the screen and make it visible.
Now this code is called from the event dispatching thread, so when the showSplashScreen() method is called, I don't get to see the JWindow until the thread has finished, which by then, I don't need the window anymore. What would be the best way to go about showing this splash screen while I was waiting?
Solution
Not sure if this is the "best way", but a mechanism I've used before is to do your initialisation on a thread other than the EDT, but show your splash screen using SwingUtilities.invokeAndWait
. That way, you'll at least get to see the splash screen even if your initialisation is quick (if that's what you want to happen).
So on your init thread, you go:
SwingUtilities.invokeAndWait( /* Runnable to show splash screen */ );
// Do stuff that takes time.
SwingUtilities.invokeLater( /* Hide splash screen, display main GUI */ );
OTHER TIPS
There is a java.awt.SplashScreen
class that was introduced in 1.6, tried using that?