Solved

Background image not showing up on JFrame

Posted on 2004-08-23
36
510 Views
Last Modified: 2013-11-23
I have posted my code at http://sourcepost.sytes.net/sourceview.aspx?source_id=16191

I am getting my JFrame to load up and loading my image through the try catch statement.   When it runs however all I see if a grey background with no background image which is called "sand.jpg"   Anyone can provide the solution then that would be very nice.  

This is the first of many many questions that is related to game many of which will be 500 points :)  
0
Comment
Question by:pjcrooks2000
  • 13
  • 11
  • 10
  • +1
36 Comments
 
LVL 35

Expert Comment

by:girionis
ID: 11869024
Do you get any error messages?
0
 
LVL 35

Expert Comment

by:girionis
ID: 11869030
I have also noticed that the source code is missing most of the curly brackets... Why is that?
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11869035
1) can you post your code here, it's been garbled on that other site...
2)  You seem to get the graphics object every time round your run() method, and dispose of it!  This is really wasteful, just get it at the top of run
3)  You are calling getGraphics() on the JFrame object, wheras you really want to be calling it on:  this.getContentPane().getGraphics() ;
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11869039
Nope no errors gironis

Looks like the postfag website had removed the brackets from the code I have uploaded the file, just click on download link from here hopefully that will work

http://sourcepost.sytes.net/sourceview.aspx?source_id=16192
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11869047
TimTates I have just uploaded the file as in last post, can you ellaborate once you have had a chance to try it out

thanks
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11869053
> Looks like the postfag website had removed the brackets from the code I have uploaded the file,

Because it thinks it's pascal code...

Can you just post it here?  It will help people answer your question, and help others in the future see what the problem was, and how it was solved :-)
0
 
LVL 35

Expert Comment

by:girionis
ID: 11869059
I still can't see it properly :(
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11869062
Yeah sure no problemo I just dont want to make it too confusing yes but good idea :)

package myprojects.jaysnake;

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


class JaySnake extends JFrame implements Runnable {
      
      private Thread gamePlay;
      private BufferedImage backBuffer;
      private Graphics myBackBuffer;
      
      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);
      
/******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");
      
      }                        
            addWindowListener(new WindowAdapter() {
                  public void windowClosing(WindowEvent e) {
                        dispose();
                        System.exit(0);
                  }
            });
            
            backBuffer = new BufferedImage(DISPLAY_W, DISPLAY_H, BufferedImage.TYPE_INT_RGB);
            myBackBuffer = backBuffer.getGraphics();
            
            //setVisible(true);
            
            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 run()
      
            {
            long startTime, waitTime, elapsedTime;
        //      1000/25 Frames Per Second = 40millisecond delay
        int delayTime = 1000/25;
            
            Thread thisThread = Thread.currentThread();
            while(gamePlay==thisThread)
            {
             
                  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");
            
            dispose();
            System.exit(0);
      }

      public static void main(String args[]) {
            System.out.println("Starting JaySnake...");
            JaySnake mainFrame = new JaySnake();
            mainFrame.setSize(DISPLAY_W, DISPLAY_H);
            mainFrame.setTitle("JaySnake Game");
            mainFrame.setVisible(true);
            
            JaySnake app = new JaySnake();
            app.gamePlay = new Thread(app);
            app.gamePlay .start();
      }
      
      /*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

            g.drawImage(backgroundImage,0,0,null);
            
/******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);      
      }
      
/******declared class variables/containers*/
   private Image backgroundImage;
}


There you go !
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11869067
 public void run()
  {
    long startTime, waitTime, elapsedTime ;
    //      1000/25 Frames Per Second = 40millisecond delay
    int delayTime = 1000 / 25 ;
    Thread thisThread = Thread.currentThread() ;
    Graphics g = getContentPane().getGraphics() ;
    while( gamePlay == thisThread )
    {
      startTime = System.currentTimeMillis() ;
      render( myBackBuffer ) ;
      // render back buffer image to screen
      g.drawImage( backBuffer, DISPLAY_X, DISPLAY_Y, null ) ;
      //  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" ) ;
    System.exit( 0 ) ;
  }

0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11869082
I just swapped that over for my ruin method and still no luck.

The image sand.jpg is in the roof folder as my code, spooky!  
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11869090
You might be better extending JPanel, and putting your code in there, then adding this JPanel to a JFrame

That way, you should be able to simply add the JPanel to a JApplet if you want to do it as an applet at a later date :-)

Tim
0
 
LVL 6

Expert Comment

by:expertmb
ID: 11869095
you can download the source there is  a download as file link is there.
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11869097
Does it draw the rest of the stuff?

Just not the image?
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11869102
>  you can download the source there is  a download as file link is there.

Yeah, it's still better having it here too ;-)
0
 
LVL 35

Expert Comment

by:girionis
ID: 11869106
I think you should put the painting in your a paint method otherwise you won't be able to draw the backgroudn image.
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11869110
Actually Tim didn't think about that, but no it does not draw the other stuff on there.
0
 
LVL 35

Expert Comment

by:girionis
ID: 11869112
Then as Tim saied, put the panel in the frame.
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11869123
try:

      backgroundImage = ImageIO.read( JaySnake.class.getResource( "/sand.jpg" ) ) ;

assuming sand.jpg is with the myprojects folder of your classes...
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11869128
If I put it into a panel can I have a menubar on the frame?   I changed Jframe to JPanel and its thrown some problems up regard get.contentpane set.resizable and so on

0
 
LVL 35

Expert Comment

by:girionis
ID: 11869135
Yes you can. Add both the JMenuBar and the JPanel (with your image as background) to your JFrame.
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11869141
Ok I will try to convert that to JPanel give me a few :)
0
 
LVL 35

Expert Comment

by:girionis
ID: 11869145
>  I changed Jframe to JPanel and its thrown some problems up regard get.contentpane set.resizable and so on

Either extend JPanel and add it to a JFrame or extend JFrame and have a separate class to act as JPanel and add it to your class (JFrame).
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11869154
What about using a Canvas?
0
 
LVL 6

Expert Comment

by:expertmb
ID: 11869172
>>while(gamePlay==thisThread)
where this gamePlay is getting its value.
0
 
LVL 35

Expert Comment

by:girionis
ID: 11869178
You can use a Canvas if you want to.
0
 
LVL 35

Assisted Solution

by:girionis
girionis earned 75 total points
ID: 11869181
The problem is with the Graphics object, it is null since it is not initialized properly inside a JFrame. So you get a npe and the grey window on the screen.
0
 
LVL 35

Accepted Solution

by:
TimYates earned 425 total points
ID: 11869183
Try:

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: 11869185

So go on then tell me how :) I want to give out  alof of point but if I have to go off and spend ages I can't do that.. be nice to move through it quite quick if you know what i mean ;)
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11869199
Whooooaaa Tim you the man on that one.

It works there, what did you do if you don't mind telling me :)  Hmmmm gironis I will give a token for your assistance but please watch for the next one that will be to do with adding a menubar to my app.  I expect that will  be within ghte next couple of hrs unless you want me to just post it now and you can have a go.  

Thanks guys
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11869210
Look out for this one now setting up a JFrame to use multiple images for a background.  ie 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 chaneg it thereon.

thansk will split points now and repost a question

pjcrooks
0
 
LVL 35

Expert Comment

by:girionis
ID: 11869217
It's fine with me, you don't have to give me any points. Tim is worth them since he posted a complete solution :)

As for the menu, post it whenever you feel (if you ever feel, you might as well manage on your own) you are stuck.
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11869221
Oakies I always to award effort ... But the best one gets most maybe thats not right I don't know ...
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11869223
1) Ok, you were creating two frames in your main method (for some reason)
2) I added the new "Game" class, which extends JPanel
3) I made "Game" implement runnable instead of the JFrame class
4) I moved the getGraphics call to outside the while loop inside run (so you only get it once)
5) I changed the while loop, as it was always failing (after I moved it all to the Game class)...  I added a "running" boolean, which you can set to false when you want to stop the game :-)
6) Errr... I think that's it ;-)

Tim
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11869226
Seems fair to me :-)

Good luck with it :-)

Glad I could help :-)

Tim
0
 
LVL 35

Expert Comment

by:girionis
ID: 11869244
:)
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11869245
Sheeeeesh amazing.....   your good I give you that.  I need to learn more :)

I suppose its my own fault for going straight in at level three and missing out level one and two .. I can blame my university for allowing me to aswell ... buggers  
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Application launch issue with Apache Tomcat 5 19
VB Script to add site to Java Exception List 4 48
Java JRE greater than 1.6 5 49
javap bin 2 25
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
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…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

929 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

12 Experts available now in Live!

Get 1:1 Help Now