Drawing Rectangles That Wont Disappear
In your code, you've created a MyPanel class that extends JPanel. Within this class, you define a method DrawRect that takes several arguments to draw a rectangle. However, when you call repaint(), it redraws the entire panel, including the previous rectangles.
To prevent this, you can instead use Graphics2D.drawImage() to draw your rectangle on top of the existing canvas. Here's how you can modify your code:
<code class="java">class MyPanel extends JPanel { private BufferedImage canvasImage; // Create a BufferedImage to store the canvas public void DrawRect(int x, int y, int size, Color c) { if (canvasImage == null) { canvasImage = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D g = canvasImage.createGraphics(); g.setColor(getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); g.dispose(); } Graphics2D g = canvasImage.createGraphics(); g.setColor(c); g.fillRect(x, y, size, size); g.dispose(); repaint(); } @Override public void paint(Graphics g) { super.paint(g); g.drawImage(canvasImage, 0, 0, null); // Draw the canvasImage onto the panel } }</code>
Note:
The above is the detailed content of How to Draw Rectangles That Won\'t Disappear on a JPanel?. For more information, please follow other related articles on the PHP Chinese website!