Link to home
Start Free TrialLog in
Avatar of pjcrooks2000
pjcrooks2000

asked on

Adding a splash screen to my java game

Ok here smy code at the moment for my game class:::
-----------------------------------------------------------------

import java.awt.*;
import java.awt.event.*;
import java.awt.* ;
import java.awt.event.* ;
import java.awt.image.* ;
import javax.imageio.* ;
import java.io.* ;
import javax.swing.* ;

public class JaySnake extends JFrame
{
  class Game extends JPanel implements Runnable
  {
    private BufferedImage backBuffer ;
    private Graphics myBackBuffer ;

    public Game()
    {

      /******Try read in backgroundImage file and catch any exception*/
      try
      {
        backgroundImage = ImageIO.read( new File( "default.jpg" ) );
        backgroundImage = ImageIO.read( new File( "blueGlass.jpg" ) );
        backgroundImage = ImageIO.read( new File( "grassBack.jpg" ) );
        backgroundImage = ImageIO.read( new File( "sand.jpg" ) );
      }
      catch( IOException e )
      {
        System.out.println( "Cannot load image file!" ) ;
      }
      backBuffer = new BufferedImage( DISPLAY_W, DISPLAY_H, BufferedImage.TYPE_INT_RGB ) ;
      myBackBuffer = backBuffer.getGraphics() ;

//set up the menubar
      menubar = new JMenuBar();
      setJMenuBar(menubar);

    }

    long startTime, waitTime, elapsedTime ;
    public void paintComponent( Graphics g )
    {
      g.drawImage( backBuffer, DISPLAY_X, DISPLAY_Y, null ) ;
    }

    public void run()
    {
      //     1000/25 Frames Per Second = 40millisecond delay
      int delayTime = 1000 / 25 ;

      Thread thisThread = Thread.currentThread() ;
      while( running )
      {
        startTime = System.currentTimeMillis() ;
        // render to back buffer now
        render( myBackBuffer ) ;

        repaint() ;
        //  handle frame rate
        elapsedTime = System.currentTimeMillis() - startTime ;
        waitTime = Math.max( delayTime - elapsedTime, 5 ) ;

        try
        {
          Thread.sleep( waitTime ) ;
        }
        catch( InterruptedException e )
        {}
      }
      System.out.println( "Program Exited" ) ;
    }

   
  }

  private Thread gamePlay ;
  private boolean running = true ;
  private Game game ;

  private final int DISPLAY_X ; // value assigned in constructor
  private final int DISPLAY_Y ; // value assigned in constructor

  private static final int DISPLAY_W = 600 ;
  private static final int DISPLAY_H = 600 ;

  int size, hsize = 0, score1 = 0, score2 = 0, highscore = 0 ;

  /****Creates JMenuBar */
  private JMenuBar menubar ;
  /****Creates JMenu to house items */
  private JMenu gameMenu = new JMenu( "Game" ) ;
  private JMenuItem gameStart = new JMenuItem( "Start" ) ;
  private JMenuItem gameQuit = new JMenuItem( "Quit" ) ;

  private JMenu bgMenu = new JMenu( "Backgrounds" ) ;
  private ButtonGroup bgGroup = new ButtonGroup() ;
  private JRadioButtonMenuItem bg1 = new JRadioButtonMenuItem( "Default" ) ;
  private JRadioButtonMenuItem bg2 = new JRadioButtonMenuItem( "Long grass" ) ;
  private JRadioButtonMenuItem bg3 = new JRadioButtonMenuItem( "Yellow Sand" ) ;
  private JRadioButtonMenuItem bg4 = new JRadioButtonMenuItem( "Blue Glass" ) ;

  private JMenu soundMenu = new JMenu( "Enable sounds" ) ;
  private JCheckBoxMenuItem soundMusic = new JCheckBoxMenuItem( "Music" ) ;
  private JCheckBoxMenuItem soundSound = new JCheckBoxMenuItem( "Sounds" ) ;

  private JMenu helpMenu = new JMenu( "Help" ) ;
  private JMenuItem userInstruct = new JMenuItem( "User Instructions" ) ;
  private JMenuItem helpAbout = new JMenuItem( "About" ) ;

  /******JaySnake constructor*/
  public JaySnake()
  {
    /*****Sets title for main window*/
    //setTitle("JaySnake Game");
    //getContentPane().setLayout( new BorderLayout() ) ;
    //setResizable( false ) ;
    //Causes Menu Titles to not show up when un commented
    //setIgnoreRepaint( true ) ;
    game = new Game() ;
    getContentPane().add( game, BorderLayout.CENTER ) ;
    this.setJMenuBar( menubar );

    menubar.add( gameMenu ) ;
    gameMenu.add( gameStart ) ;
    gameMenu.add( gameQuit ) ;

    // ActionListener to quit the game when quit is clicked
    gameQuit.addActionListener( new ActionListener(){  
   
               public void actionPerformed( ActionEvent e )
     {
        System.exit( 0 );
     }
      } ) ;                                                  
                         
    menubar.add( bgMenu ) ;
    bgMenu.add( bg1 ) ;
    bgMenu.add( bg2 ) ;
    bgMenu.add( bg3 ) ;
    bgMenu.add( bg4 ) ;

    bgGroup.add( bg1 ) ;
    bgGroup.add( bg2 ) ;
    bgGroup.add( bg3 ) ;
    bgGroup.add( bg4 ) ;

    menubar.add( soundMenu ) ;
    soundMenu.add( soundMusic ) ;
    soundMenu.add( soundSound ) ;

    menubar.add( helpMenu ) ;
    helpMenu.add( userInstruct ) ;
    helpMenu.add( helpAbout ) ;

    addWindowListener( new WindowAdapter()
    {
      public void windowClosing( WindowEvent e )
      {
        dispose();
        System.exit( 0 ) ;
      }
    } ) ;

    Insets insets = getInsets() ;
    DISPLAY_X = insets.left ;
    DISPLAY_Y = insets.top ;
    resizeToInternalSize( DISPLAY_W, DISPLAY_H ) ;
  }

  public void resizeToInternalSize( int internalWidth, int internalHeight )
  {
    Insets insets = getInsets() ;
    final int newWidth = internalWidth + insets.left + insets.right ;
    final int newHeight = internalHeight + insets.top + insets.bottom ;

    Runnable resize = new Runnable()
    {
      public void run()
      {
        setSize( newWidth, newHeight ) ;
      }
    } ;

    if( !SwingUtilities.isEventDispatchThread() )
    {
      try
      {
        SwingUtilities.invokeAndWait( resize ) ;
      }
      catch( Exception e )
      {}
    }
    else
      resize.run() ;

    validate() ;
  }

  public void start()
  {
    Thread gamePlay = new Thread( game ) ;
    gamePlay.start() ;
  }

  public static void main( String args[] )
  {
    System.out.println( "Starting JaySnake..." ) ;
    JaySnake app = new JaySnake() ;
    app.setSize( DISPLAY_W, DISPLAY_H ) ;
    app.setTitle( "JaySnake Game" ) ;
    app.setVisible( true ) ;
    app.start() ;
  }

/*Render method for graphics content*/
    public void render( Graphics g )
    {
     if( backgroundImage != null )
        g.drawImage( backgroundImage, 0, 0, this ) ;

      /******Draw scoreboard and player details, sets color for score and player
       ******draws rectangle in same green, draws strings and used variables score1
       ******and score2. Sets color again to black draws another rectangle
       ******that is used to highlight the playing area*/
      g.setColor( Color.green ) ;
      g.drawRect( 1, 0, 598, 32 ) ;
      g.drawString( "Player 1 score: " + score1, 10, 13 ) ;
      g.drawString( "Player 2 score: " + score2, 10, 27 ) ;
      g.drawString( "High score: " + highscore, 510, 15 ) ;
      g.setColor( Color.black ) ;
      g.drawRect( 1, 34, 598, 521 ) ;
     
    }

  /******declared class variables/containers*/
  private Image backgroundImage ;
}


Now here is a class that I have that creates a Splash screen without any borders on the Window.
-------------------------------------------------------------------------------------------------------------------

class Splash extends JWindow       {
       public Splash(String filename, Frame f, int waitTime)
             {
                 super(f);
                 JLabel l = new JLabel(new ImageIcon("splash.gif"));
                 //JLabel l = new JLabel(new ImageIcon("splash.jpg"));
                 getContentPane().add(l, BorderLayout.CENTER);
                 pack();
                 
                 Dimension screenSize =
                   Toolkit.getDefaultToolkit().getScreenSize();
                 Dimension labelSize = l.getPreferredSize();
                 setLocation(screenSize.width/2 - (labelSize.width/2),
                       screenSize.height/2 - (labelSize.height/2));
                 
                 addMouseListener(new MouseAdapter()
                     {
                         public void mousePressed(MouseEvent e)
                         {
                             setVisible(false);
                             dispose();
                         }
                     });
                     
                 final int pause = waitTime = 3000;
           
                 Runnable waitRunner = new Runnable()
               {
                         public void run()
                         {
                             try
                                 {
                                     Thread.sleep(pause);
                                     setVisible(false);
                                     System.out.println("Setting Visable");
                                       dispose();
                                 }
                             catch(Exception e)
                                 {
                               e.printStackTrace();
                                     // can catch InvocationTargetException
                                     // can catch InterruptedException
                                 }
                         }
                     };
                     
                 setVisible(true);
                 Thread splashThread = new Thread(waitRunner, "SplashThread");
                 splashThread.start();
             }
   }

Now what I want to do is to have the splash screen appear before my window loads up and I want to be able to click on the splash screen that will have the effect of loading up my game window.   Any ideas?  

I need to use the class in my game - How should I do it?

Thanks guys!  
ASKER CERTIFIED SOLUTION
Avatar of girionis
girionis
Flag of Greece image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Also this will help wth regards to clickin gon the splash screen and starting the game after that: https://www.experts-exchange.com/questions/10317879/Splash-logo-screen-in-Java.html
Oh,
You posted that already
Avatar of pjcrooks2000

ASKER

Yes Gironis currently I have it working on another JFram and its all in the one file.  I wan to creat another file from the class and use it in my game as above.  Sorry if I didn't make that clear!
Is looking good for a full pointer to girionis, still gotta do it later on though once the mrs goes to bed and leaves me alone :)

Take a look at my second comment, it has sample source code of how you can do it :)
Ok coolio, actually shuuuush don't tell no one,  but the first link is where i got the splash screen code from :)  hehehe Don't you just love reusable code ?
Hehe I do :)

Thank you for accepting.
yer welcome me ole chap... Hey Kelly Holmes did well yesterday ?   You been watching Olympics at all?
Nope, I am not really into the whole Olympic Games idea :)