Java .drawImage : How do I "unDraw" or delete a image?

Saucymeatman picture Saucymeatman · Jul 25, 2013 · Viewed 15k times · Source

I need a certain image to be redrawn at different locations constantly as the program runs. So I set up a while loop that should move an image across the screen, but it just redraws the image on top of itself over and over again. What am I doing wrong? Is there a way to delete the old image before drawing it in a new location?

        JFrame frame = buildFrame();

    final BufferedImage image = ImageIO.read(new File("BeachRoad_double_size.png"));

    JPanel pane = new JPanel() {
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            int num = 0;
            boolean fluff = true;
            while (fluff == true) {
            num = num + 1;
            g.drawImage(image, num, 0, null);
            if (num == 105) {
                fluff = false;
            }
            }
        }
    };


    frame.add(pane);

Answer

camickr picture camickr · Jul 25, 2013

You can't code a loop in the paintComponent() method. The code will execute so fast that the image will only be painted in the final position, which in your case should be with an x position of 105.

Instead you need to use a Swing Timer to schedule the animation every 100 milliseconds or so. Then when the timer fires you update the x position and invoke repaint() on the panel. Read the Swing tutorial on Using Swing Timers for more information.