"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Draw Rectangles Permanently in a JPanel: Using BufferedImages to Avoid Overwriting?

How to Draw Rectangles Permanently in a JPanel: Using BufferedImages to Avoid Overwriting?

Published on 2024-11-11
Browse:547

How to Draw Rectangles Permanently in a JPanel: Using BufferedImages to Avoid Overwriting?

Drawing Rectangles in a Permanent Manner

In your JPanel implementation, rectangles disappear because the paint() method overwrites previous drawings. To prevent this, we modify our approach:

Using a BufferedImage as Painting Surface

Instead of directly drawing on the JPanel, we use a BufferedImage (canvasImage) as our painting surface. This allows us to modify the image permanently without affecting previous drawings.

Customized paint() Method

Here's a modified paint() method that uses canvasImage for drawing:

@Override
public void paint(Graphics g) {
    super.paint(g); // Handle inherited painting tasks

    Graphics2D bg = (Graphics2D) g;
    bg.drawImage(canvasImage, 0, 0, this);
}

Creating the BufferedImage and Setting It Up

Initialize canvasImage in your JPanel constructor like so:

canvasImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

And set its graphics context for drawing:

Graphics2D cg = canvasImage.createGraphics();
cg.setColor(Color.WHITE);
cg.fillRect(0, 0, width, height);

Drawing Rectangles on the BufferedImage

Now, your DrawRect() method can modify canvasImage directly:

public void DrawRect(int x, int y, int size, Color c) {
    Graphics2D cg = canvasImage.createGraphics();
    cg.setColor(c);
    cg.fillRect(x, y, size, size);
}

Additional Features

This approach provides several benefits:

  • Persistent Draw: Rectangles are permanently drawn on the BufferedImage.
  • Optimized Drawing: Instead of repainting the entire JPanel, only the modified portions of the image are updated.
  • Supports Undo/Redo (Potential): By keeping track of changes to the image, you can implement undo/redo functionality.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3