Solved

Background image not showing up on JFrame

Posted on 2004-08-23
36
509 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
Comment Utility
Do you get any error messages?
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
> 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
Comment Utility
I still can't see it properly :(
0
 
LVL 8

Author Comment

by:pjcrooks2000
Comment Utility
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
Comment Utility
 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
Comment Utility
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
Comment Utility
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
Comment Utility
you can download the source there is  a download as file link is there.
0
 
LVL 35

Expert Comment

by:TimYates
Comment Utility
Does it draw the rest of the stuff?

Just not the image?
0
 
LVL 35

Expert Comment

by:TimYates
Comment Utility
>  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
Comment Utility
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
Comment Utility
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
Comment Utility
Then as Tim saied, put the panel in the frame.
0
 
LVL 35

Expert Comment

by:TimYates
Comment Utility
try:

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

assuming sand.jpg is with the myprojects folder of your classes...
0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 8

Author Comment

by:pjcrooks2000
Comment Utility
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
Comment Utility
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
Comment Utility
Ok I will try to convert that to JPanel give me a few :)
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
>  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
Comment Utility
What about using a Canvas?
0
 
LVL 6

Expert Comment

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

Expert Comment

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

Assisted Solution

by:girionis
girionis earned 75 total points
Comment Utility
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
Comment Utility
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
Comment Utility

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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Seems fair to me :-)

Good luck with it :-)

Glad I could help :-)

Tim
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
:)
0
 
LVL 8

Author Comment

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

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

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…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
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:
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

743 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

16 Experts available now in Live!

Get 1:1 Help Now