Home > Java > javaTutorial > body text

How to Draw Persistent Rectangles in a JPanel Without Performance Degradation?

Barbara Streisand
Release: 2024-10-30 05:24:02
Original
299 people have browsed it

How to Draw Persistent Rectangles in a JPanel Without Performance Degradation?

Drawing Rectangles that Persist

Problem:

Creating rectangles in a JPanel that remain visible despite repaint calls, without slowing down the system due to excessive redrawing.

Solution:

Utilize a BufferedImage as the painting surface.

Approach:

  1. Create a JPanel subclass with a BufferedImage as the canvas for drawing.
  2. Implement a paint method that draws rectangles onto the BufferedImage.
  3. Invalidate and repaint the JPanel only when necessary, such as when drawing new rectangles.
  4. Keep a list of drawn rectangles to avoid repeated drawing.

Example:

<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>
Copy after login

Advantages:

  • Rectangles remain visible without disappearing in subsequent repaints.
  • Drawing and repainting operations are optimized, eliminating performance lags.

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!