Gimv30
Gimv30

Reputation: 55

Jpanel painting not cleared

I am using a JPanel and I am trying to paint some rectangles on it when I click on the panel. After I click though, I want a new shape to appear, but the previous one to be deleted. I've tried some things however the previous shapes don't get removed and I don't know why.

public class Canvas extends JPanel {

private BufferedImage image = new BufferedImage(800, 600, BufferedImage.TYPE_INT_ARGB);
private Graphics2D graphics = image.createGraphics();

Canvas() {

    addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
            drawShapeAt(e.getX(), e.getY());
            repaint();

        }
    });

}

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(image,0,0,this);
}


public void drawShapeAt(int x, int y) {

    graphics.setColor(Color.blue);
    graphics.fill(new RegularPolygon(x, y, 100, 5));

}

}

I also call this on my JFrame.

    Canvas mouse=new Canvas();
    this.add(mouse, BorderLayout.CENTER);
    mouse.drawShapeAt(250,250);

The shapes are drawn nicely , the center is where I click but the previous ones don't get removed..I thought that by using repaint() and super.paintComponent(g) they would be removed, that's where I'm stuck...

Upvotes: 0

Views: 314

Answers (1)

camickr
camickr

Reputation: 324108

If you only ever want to draw a single shape, then there is no need for the Buffered image. That is extra overhead to clear the BufferedImage, paint on the BufferedImage, and finally repaint the BufferedImage in the paintComponent(...) method.

Instead just create instance variables in your class (like startX/startY) and then draw the rectangle in the paintComponent(...) method based on these variables. No need for the BufferedImage. This is the way Swing components paint themselves. They just paint directly using the Graphics methods.

A BufferedImage would typically only be used when you have a complicated painting that remains static.

Read the section from the Swing tutorial on Custom Paining for a working example of this approach.

I would only use the BufferedImage if you want do draw multiple Rectangles. You can also check out Custom Painting Approaches. It will show you how to clear a BufferedImage.

Upvotes: 4

Related Questions