Link to home
Start Free TrialLog in
Avatar of pjcrooks2000
pjcrooks2000

asked on

Background image not showing up on JFrame

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 :)  
Avatar of girionis
girionis
Flag of Greece image

Do you get any error messages?
I have also noticed that the source code is missing most of the curly brackets... Why is that?
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() ;
Avatar of pjcrooks2000
pjcrooks2000

ASKER

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
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
> 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 :-)
I still can't see it properly :(
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 !
 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 ) ;
  }

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!  
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
you can download the source there is  a download as file link is there.
Does it draw the rest of the stuff?

Just not the image?
>  you can download the source there is  a download as file link is there.

Yeah, it's still better having it here too ;-)
I think you should put the painting in your a paint method otherwise you won't be able to draw the backgroudn image.
Actually Tim didn't think about that, but no it does not draw the other stuff on there.
Then as Tim saied, put the panel in the frame.
try:

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

assuming sand.jpg is with the myprojects folder of your classes...
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

Yes you can. Add both the JMenuBar and the JPanel (with your image as background) to your JFrame.
Ok I will try to convert that to JPanel give me a few :)
>  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).
What about using a Canvas?
>>while(gamePlay==thisThread)
where this gamePlay is getting its value.
You can use a Canvas if you want to.
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
ASKER CERTIFIED 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

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 ;)
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
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
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.
Oakies I always to award effort ... But the best one gets most maybe thats not right I don't know ...
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
Seems fair to me :-)

Good luck with it :-)

Glad I could help :-)

Tim
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