0

I'm making a game using Java.

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

  • the LevelBuilder class which, upon it's default constructor being called will create a jframe with the required components and then run a gameloop thread which will update even 1/20th of a second using a backbuffer.
  • The other class is the MainMenu class which i want to have the main method in and to display my logo in a JFrame.

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.

Harrison Harris
  • 85
  • 2
  • 10

1 Answers1

3

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

halfer
  • 19,824
  • 17
  • 99
  • 186
David Kroukamp
  • 36,155
  • 13
  • 81
  • 138