Solved

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

Posted on 2004-08-23
11
310 Views
Last Modified: 2010-03-31

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!
0
Comment
Question by:pjcrooks2000
  • 6
  • 5
11 Comments
 
LVL 8

Author Comment

by:pjcrooks2000
Comment Utility
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 ;
}
0
 
LVL 8

Author Comment

by:pjcrooks2000
Comment Utility
Be back in about an hours guys thank you very muchly I need to nip out for a while.  
0
 
LVL 35

Accepted Solution

by:
girionis earned 500 total points
Comment Utility
This should do what you are asking for (although I need to work on the flickering):

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 implements ActionListener
{
  class Game extends JPanel implements Runnable
  {
    private BufferedImage backBuffer ;
    private Graphics myBackBuffer ;
      private File file = new File("sand.jpg");
      
      public void setImage(String fileName) throws Exception
      {
            backgroundImage = ImageIO.read( new File(fileName) ) ;
      }
      
    public Game()
    {
      
      
      /******Try read in backgroundImage file and catch any exception*/
      try
      {
        backgroundImage = ImageIO.read( new File( "green7.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 void actionPerformed(ActionEvent e)
  {
        try
      {
            JMenuItem source = (JMenuItem)(e.getSource());
            System.out.println(source.getText());
            game.setImage(source.getText());
      }
      catch (Exception ex)
      {
            System.out.println(ex);
      }
  }
            
  public JaySnake()
  {
        
          menuBar.add(menu);
   
            // Create a menu item
            JMenuItem item = new JMenuItem("background-butterfly.jpg");
            JMenuItem item2 = new JMenuItem("background-cap.jpg");
            JMenuItem item3 = new JMenuItem("background-4oclock.jpg");
            JMenuItem item4 = new JMenuItem("background-cave.jpg");
            item.addActionListener(this);
            item2.addActionListener(this);
            item3.addActionListener(this);
            item4.addActionListener(this);
            menu.add(item);
            menu.add(item2);
            menu.add(item3);
            menu.add(item4);

            // Install the menu bar in the frame
            this.setJMenuBar(menuBar);
            
    /*****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() ;
  }

  // Create the menu bar
    private JMenuBar menuBar = new JMenuBar();
   
          // Create a menu
    private JMenu menu = new JMenu("Images");
  /******declared class variables/containers*/
  private Image backgroundImage ;
}

The images overwritte each other so make sure they are of the same size. Also do not worry about the names of the images I use, I downloaded some random ones from the internet. Just replace the manu items with the images you have.
0
 
LVL 8

Author Comment

by:pjcrooks2000
Comment Utility
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 ...  :)
0
 
LVL 35

Assisted Solution

by:girionis
girionis earned 500 total points
Comment Utility
I create the manu bar with the images already.
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 8

Author Comment

by:pjcrooks2000
Comment Utility
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 :)

0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
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 :)
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
:)
0
 
LVL 8

Author Comment

by:pjcrooks2000
Comment Utility
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 !  
0
 
LVL 8

Author Comment

by:pjcrooks2000
Comment Utility
I mean girionis .. sorry :)
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
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.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Return ZipOutputStream using Servlet 2 32
commonTwo  challenge 63 98
countHi challenge 25 84
mapBully challenge 6 88
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

762 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

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now