?
Solved

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

Posted on 2004-08-23
11
Medium Priority
?
351 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
11 Comments
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11869233
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
ID: 11869262
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 2000 total points
ID: 11869373
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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11870486
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 2000 total points
ID: 11870828
I create the manu bar with the images already.
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11871113
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
ID: 11871145
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
ID: 11871148
:)
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11871179
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
ID: 11871353
I mean girionis .. sorry :)
0
 
LVL 35

Expert Comment

by:girionis
ID: 11871557
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

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

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

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This video teaches viewers about errors in exception handling.
Suggested Courses
Course of the Month9 days, 7 hours left to enroll

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