In your JPanel implementation, rectangles disappear because the paint() method overwrites previous drawings. To prevent this, we modify our approach:
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.
Here's a modified paint() method that uses canvasImage for drawing:
<code class="java">@Override public void paint(Graphics g) { super.paint(g); // Handle inherited painting tasks Graphics2D bg = (Graphics2D) g; bg.drawImage(canvasImage, 0, 0, this); }</code>
Initialize canvasImage in your JPanel constructor like so:
<code class="java">canvasImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);</code>
And set its graphics context for drawing:
<code class="java">Graphics2D cg = canvasImage.createGraphics(); cg.setColor(Color.WHITE); cg.fillRect(0, 0, width, height);</code>
Now, your DrawRect() method can modify canvasImage directly:
<code class="java">public void DrawRect(int x, int y, int size, Color c) { Graphics2D cg = canvasImage.createGraphics(); cg.setColor(c); cg.fillRect(x, y, size, size); }</code>
This approach provides several benefits:
The above is the detailed content of How to Draw Rectangles Permanently in a JPanel: Using BufferedImages to Avoid Overwriting?. For more information, please follow other related articles on the PHP Chinese website!