How to use images in JFrame's and JComponent's

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Corey S
    New Member
    • May 2010
    • 1

    How to use images in JFrame's and JComponent's

    Hey, I'm trying to make a game for a school project that uses image files. I've been working on changing some pre-written code (I believe from IBM) that we used for pong as I'm not yet an expert on swing; however, the pre-written code only allows for the insertion of solid colored objects, not images. The pre-written code was divided into Game (which was a child of JFrame) and GameObject (which was a child of JComponent). The original paint method in GameObject was

    Code:
     public void paint(Graphics g) {
      Rectangle r = getBounds();
      g.setColor(c);
      g.fillRect(0, 0, (int)r.getWidth(), (int)r.getHeight());
     }
    I changed it to be
    Code:
    public void paint(Graphics g) {
     g.drawImage(image, getX(), getY(), this);
    }
    Where image has already been declared and constructed as follows
    Code:
    BufferedImage image;
    try {
            String path = "images/spaceship.png";
            URL url = getClass().getResource(path);
            image = ImageIO.read(url);
        }
        catch (IOException e)
        {
          System.out.println("not valid image");
        }
    Unfortunately when I run the game, the GameObject does not appear at all in the JFrame, except when I move it into the top left corner of the screen.

    I'm also not sure if I should use a BufferedImage or a normal Image to construct my image, and what the best way to construct it would be.

    Any help would be appreciated, thanks.
Working...