Search code examples
javaswinggraphicsgraphics2d

Java Graphics2D Image Moving


So in this block of code, a 40x40 square can move across a window by calling directional methods, and I'm trying to get a spaceship to appear instead of the square. No matter what I try, it just isn't working.

public void paintComponent (Graphics g) {

        ImageIcon wallpaper = new ImageIcon("images/JGalagawallpaper.png");
        image = wallpaper.getImage();
        g.drawImage(image, 400, 400, null);

        ImageIcon ship = new ImageIcon("images/galaga.png");
        galaga = ship.getImage();


        super.paintComponent(g);
        Graphics2D graphic = (Graphics2D) g;
        graphic.fill(new Rectangle.Double(x, y, 40, 40));
        //graphic.drawImage(galaga, x, y, 40, 40);
    }

My question is, how do I get that thing to appear? I already tried tinkering with graphic.drawImage, however that didn't really work out as well as I hoped. That's what the commented out code is.


Solution

  • g.drawImage(image, 400, 400, null);
    

    First you draw the image.

    super.paintComponent(g);
    

    Then you invoke the above code which is used to pint the background color of the panel, thus overwriting the image. The above statement should be the first statement of the painting method.

    ImageIcon wallpaper = new ImageIcon("images/JGalagawallpaper.png");
    

    A painting method is for painting only. Don't do I/O in the method. The image should be read in the constructor of your class so that it is only read once, not every time the component is repainted.

    You also need to look at the coordinates of where you paint the image. Maybe the panel is not that big?

    Did you verify that the image was read properly by display its size?