Home  >  Article  >  Java  >  How to Draw Persistent Rectangles in a JPanel: Avoiding Disappearance on Repaint?

How to Draw Persistent Rectangles in a JPanel: Avoiding Disappearance on Repaint?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-29 11:04:02703browse

How to Draw Persistent Rectangles in a JPanel: Avoiding Disappearance on Repaint?

Drawing a Rectangle That Won't Disappear in Next Paint

Issue:

You need to create a JPanel that draws rectangles that remain visible even when the repaint method is called repeatedly.

Proposed Solution:

Instead of creating a list of rectangles and redrawing them every time the JPanel is repainted, consider using a BufferedImage as the painting surface. This approach allows for persistent drawing that won't disappear during repaints.

Implementation:

  1. Create a BufferedImage to serve as the drawing surface.
  2. Draw the rectangle on the BufferedImage using the Graphics2D object.
  3. Display the BufferedImage in the JPanel's paintComponent method.

Example Code:

<code class="java">class MyPanel extends JPanel {
    private BufferedImage canvasImage;

    // ...

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(canvasImage, 0, 0, this);
    }
}</code>

By using this approach, the rectangle will remain visible on the JPanel even after repeated repaint calls, as it is drawn directly on the BufferedImage.

The above is the detailed content of How to Draw Persistent Rectangles in a JPanel: Avoiding Disappearance on Repaint?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn