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:
@Override
public void paint(Graphics g) {
super.paint(g); // Handle inherited painting tasks
Graphics2D bg = (Graphics2D) g;
bg.drawImage(canvasImage, 0, 0, this);
}
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);
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);
}
This approach provides several benefits:
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