views:

30

answers:

2

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?

A: 

There is a java.awt.SplashScreen class that was introduced in 1.6, tried using that?

Qwerky
I don't think that's exactly what i'm looking for. But even if it was, the computers at university have issues running 1.6...
DanieL
+4  A: 

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 */ );
Ash
That's indeed the way to do, whatever you choose to use as class.
Riduidel
I tried to use invokeAndWait/invokeLater, but apparently I can't because I'm already in the EDT, so I can't use them from there...Exception in thread "AWT-EventQueue-0" java.lang.Error: Cannot call invokeAndWait from the event dispatcher thread
DanieL
Ah, I misread you, you meant to do the above code in a separate thread? It is actually in the actionPerformed method of an ActionListener because it is called when the user clicks a button, so should I create a new Thread at that point to take care of it?
DanieL
Well...I guess. But then, why are you displaying a splash screen if your application is already running?
Ash
Bleh, that's just what I called it. It's just a borderless window that says "Loading..." that I want to overlay the application window while it loads a file.
DanieL
Ah, in that case, you might want to investigate the SwingWorker (http://download.oracle.com/javase/6/docs/api/javax/swing/SwingWorker.html). It lets you offload a process and make periodic updates on the EDT, handling all the threading stuff. Current Oracle JVM has a nasty bug (http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6880336), but it is (conceptually) the correct thing to use.
Ash
And https://swingworker.dev.java.net/ has a Java 5 version of the same class.
Carey