Home > Java > javaTutorial > How to Draw Rectangles That Won\'t Disappear on a JPanel?

How to Draw Rectangles That Won\'t Disappear on a JPanel?

Patricia Arquette
Release: 2024-11-05 06:23:01
Original
750 people have browsed it

How to Draw Rectangles That Won't Disappear on a JPanel?

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

Note:

  • This approach creates a BufferedImage as the drawing surface, which persists across repaint calls, allowing you to draw rectangles that do not disappear.
  • Remember to check if canvasImage is null and initialize it before drawing to avoid drawing on a blank canvas.
  • In paint, draw the canvasImage onto the panel to display the rectangles.

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!

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