Link to home
Start Free TrialLog in
Avatar of pjcrooks2000
pjcrooks2000

asked on

Jframe background image I want to use multiple images from a menu


At present I have the JFrame working with one image for the Background at a time.  

I have 4 images I want to be able to change them via a menu eventually but I want to store them in a media container perhaps and use a switch of some sort to switch them for now until I have my menu up and running.  The menu will have a tab that says Background and four options to change it thereon. Here is the code below if you can provide a solution then great.  Perhaps a small description as to how this would work on a menubar/tab.

Don't do the menubar for me I will post that later thanks all!
Avatar of pjcrooks2000
pjcrooks2000

ASKER

Ooops code

package myprojects.jaysnake;

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( "sand.jpg" ) ) ;
      }
      catch( IOException e )
      {
        System.out.println( "Cannot load image file- The one that got away" ) ;
      }
      backBuffer = new BufferedImage( DISPLAY_W, DISPLAY_H, BufferedImage.TYPE_INT_RGB ) ;
      myBackBuffer = backBuffer.getGraphics() ;
    }

    public void run()
    {
      long startTime, waitTime, elapsedTime ;
      //     1000/25 Frames Per Second = 40millisecond delay
      int delayTime = 1000 / 25 ;

      Thread thisThread = Thread.currentThread() ;
      while( running )
      {

        startTime = System.currentTimeMillis() ;
        //snake.movePosition(2);
        //snake2.movePosition(4);
        // handle mouse events in main gamePlay
        //keyLinkedList.processKeyEventList();
        // render to back buffer now
        render( myBackBuffer ) ;

        // render back buffer image to screen
        Graphics g = getGraphics() ;
        g.drawImage( backBuffer, DISPLAY_X, DISPLAY_Y, null ) ;
        g.dispose() ;

        //  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" ) ;
    }

    /*Render method for graphics content*/
    public void render( Graphics g )
    {
      /*g.setColor(Color.black);
                 g.fillRect(0,0,DISPLAY_WIDTH,DISPLAY_HEIGHT);*/
      //not sue whether to use this aswell as background

      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 ) ;

      //snake.render(g);
      //snake2.render(g);
    }
  }

  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 ;

  /******JaySnake constructor*/

  public JaySnake()
  {
    /*****Sets title for main window*/
    //setTitle("JaySnake Game");
    getContentPane().setLayout( new BorderLayout() ) ;
    setResizable( false ) ;
    setIgnoreRepaint( true ) ;
    game = new Game() ;
    getContentPane().add( game, BorderLayout.CENTER ) ;

    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() ;
  }

  /******declared class variables/containers*/
  private Image backgroundImage ;
}
Be back in about an hours guys thank you very muchly I need to nip out for a while.  
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
Hi Gironis thanks for that I will come back to this question later, but for now I need to create my menubar.

I will post a question on menubar now and get back to this one later ...  :)
SOLUTION
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
Hey gironis I didn't realise you had done that.

Good job, I have updated the next question regarding the menu items and tried to explain it a bit better but this does certaily create a menu bar and disply how it should be done.  You the man!  points on the way---- will continue it though in next question I thinks :)

The only problem was the flickering of the jmenu which I solved by adding a mouseListener on that. If you want the updated code let me know :)
Cool ironis this is great!   The question after this one was answered by Tim so I am posting a new one to do with the menu titles :)

There will be plenty more where this lot came from trust me !  
I mean girionis .. sorry :)
I noticed something weird with this code. I just run it on my home (under Windows) and it does not display the title of the JMenu while it works on Linux!!! I have both jdk1.4 but with slightly different subversions 1.4.1_0xx and 1.4.2_0xx. Weird.