Solved

Adding a splash screen to my java game

Posted on 2004-08-24
11
311 Views
Last Modified: 2008-02-01
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!  
0
Comment
Question by:pjcrooks2000
  • 5
  • 4
  • 2
11 Comments
 
LVL 35

Accepted Solution

by:
girionis earned 500 total points
ID: 11884055
0
 
LVL 35

Expert Comment

by:girionis
ID: 11884090
Also this will help wth regards to clickin gon the splash screen and starting the game after that: http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_10317879.html
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 11884316
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 11884337
Oh,
You posted that already
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11884949
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!
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11885594
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 :)

0
 
LVL 35

Expert Comment

by:girionis
ID: 11886311
Take a look at my second comment, it has sample source code of how you can do it :)
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11886512
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 ?
0
 
LVL 35

Expert Comment

by:girionis
ID: 11886612
Hehe I do :)

Thank you for accepting.
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11887802
yer welcome me ole chap... Hey Kelly Holmes did well yesterday ?   You been watching Olympics at all?
0
 
LVL 35

Expert Comment

by:girionis
ID: 11889622
Nope, I am not really into the whole Olympic Games idea :)
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question