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

16,020

Solution 1

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.

Solution 2

Putting a while loop inside a paintComponent method is not the way to do it. Instead, there should be some setup like the following:

...
final int num = 0;
final JPanel pane;
Timer timer = new Timer(10, new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        num++;
        pane.repaint();
    }
});
pane = new JPanel() {
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, num, 0, null);
    }
});

timer.start();

This will move the image ever 10 milliseconds, as specified in the Timer constructor.

Share:
16,020
Saucymeatman
Author by

Saucymeatman

Updated on September 05, 2022

Comments

  • Saucymeatman
    Saucymeatman over 1 year

    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);