Question

Im making a small program that needs previous graphics to stay "put" and visible, even after a repaint causes a variable location to change.

    public void paint(Graphics g){
    super.paint(g);

    g.setColor(Color.red);
    g.fillOval(mouseLocX,mouseLocY,30,30);

}

this is all i have in the paint class, and i want to change the mouseLocX and mouseLocY values, and call repaint without having the previous location there. Ive done this before, and most people want the opposite, but i forgot how. Im calling repaint from a MouseMotionListener using mouseDragged();

Was it helpful?

Solution

If you want to preserve what's already been painted so that you get a trail of red ovals instead of a single red oval as the mouse moves, then you shouldn't paint directly on the Graphics object provided by paint(). Instead, use a BufferedImage to store your state. Then render the BufferedImage onto the Graphic provided by paint().

private BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

public void paint(Graphics g) {
    super.paint(g);

    Graphics imageGraphics = image.getGraphics();
    imageGraphics.setColor(Color.red);
    imageGraphics.fillOval(mouseLocX,mouseLocY,30,30);

    g.drawImage(image, 0, 0, null);
}

The BufferedImage provides the persistence for the previous draw operations.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top