Harrison Harris
Harrison Harris

Reputation: 85

How to write a splash screen?

I'm making a game using Java.

At the moment, I have several classes. The important ones are:

In the end I want to have the MainMenu draw a splash screen to the JFrame, and then after 5 seconds the LevelBuilder to draw inside the original JFrame, without creating a new one.

Sorry if it's a basic question, I just started learning Java.

Upvotes: 0

Views: 126

Answers (1)

David Kroukamp
David Kroukamp

Reputation: 36423

Well a splash-screen can simply be added to your jar via the manifest.

The problem is by default it will only show for as long as it takes Swing app to load. Thus the 2nd (3rd 4th etc) execution(s) shows the splash-screen fast as JVM and classes etc used by GUI have already been loaded.

In my game to create a splash that stays for longer I had these 2 methods:

/**
 * This will render the splash for longer than just loading components
 *
 * @return true if there is a splash screen file supplied (set via java or
 * manifest) or false if not
 * @throws IllegalStateException
 */
private boolean showSplash() throws IllegalStateException {
    final SplashScreen splash = SplashScreen.getSplashScreen();
    if (splash == null) {
        return false;
    }
    Graphics2D g = splash.createGraphics();
    if (g == null) {
        return false;
    }
    for (int i = 0; i < 100; i++) {//loop 100 times and sleep 50 thus 100x50=5000milis=5seconds
        renderSplashFrame(g);
        splash.update();
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
        }
    }
    splash.close();
    return true;
}

private void renderSplashFrame(Graphics2D g2d) {
    //draw anyhting else here
}

which will be called something like:

JFrame frame=...;

 ...

//show splash
if (!showSplash()) {
     JOptionPane.showMessageDialog(null, "SplashScreen could not be shown!", "Splash Error: 0x003", JOptionPane.ERROR_MESSAGE);
 }

// set JFrame visible
frame.setVisible(true);
frame.toFront();

Please note as showSplash() says it will return false if there is no splash-screen supplied i.e you have not added one to the manifest.

I also would recommend a read on How to Create a Splash Screen if you already haven't.

Also see this other similar answer/question: Make splash screen with progress bar like Eclipse

Upvotes: 3

Related Questions