Creating rectangles in a JPanel that remain visible despite repaint calls, without slowing down the system due to excessive redrawing.
Utilize a BufferedImage as the painting surface.
<code class="java">// Relevant JPanel subclass class MyPanel extends JPanel { private BufferedImage canvasImage; // Image for drawing rectangles // Draw a rectangle public void drawRect(int x, int y, int width, int height) { Graphics2D g = canvasImage.createGraphics(); g.setColor(Color.RED); g.fillRect(x, y, width, height); g.dispose(); repaint(); // Redraw the panel with updated canvasImage } // Update view @Override public void paint(Graphics g) { super.paint(g); g.drawImage(canvasImage, 0, 0, null); // Draw the canvasImage on the panel } }</code>
The above is the detailed content of How to Draw Persistent Rectangles in a JPanel Without Performance Degradation?. For more information, please follow other related articles on the PHP Chinese website!