JPanel custom drawing using Graphics

2019-02-17 17:54发布

I have a custom JPanel and sometimes throughout my program, I need to call a method which paints the screen black, that's it.

public void clearScreen() {
    Graphics g = getGraphics();
    g.setColor(Color.black);
    g.fillRect(0,0,getWidth(),getHeight());
}

When I launch the program, I call this method.

However, I find that sometimes it works, and sometimes it doesn't. It's very odd. I also found out that when it doesn't work, the graphics object is NOT null, and the width and height are also correctly defined (from getWidth() and getHeight()).

Why would this sometimes work and sometimes not work?

What is the correct way to make a custom drawing on my JPanel at some point in the program? Is it correct to use getGraphics() as I am doing? My JPanel (at some point) has JComponents, but later on I remove those JComponents and do some custom graphics drawing. Why would this sometimes only work?

1条回答
萌系小妹纸
2楼-- · 2019-02-17 18:20

Don't get your Graphics object by calling getGraphics on a component such as a JPanel since the Graphics object obtained will not persist on the next repaint (which is likely the source of your problems).

Instead, consider doing all of your drawing in a BufferedImage, and then you can use getGraphics() to your heart's content. If you do this, don't forget to dispose of the Graphics object when you're done painting with it.

e.g.,

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class MyPaint extends JPanel {
   public static final int IMG_WIDTH = 400;
   public static final int IMG_HEIGHT = IMG_WIDTH;

   private BufferedImage image = new BufferedImage(IMG_WIDTH, IMG_HEIGHT,
            BufferedImage.TYPE_INT_ARGB);

   public MyPaint() {
      MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
      addMouseListener(myMouseAdapter);
      addMouseMotionListener(myMouseAdapter);
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      if (image != null) {
         g.drawImage(image, 0, 0, null);
      }
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(IMG_WIDTH, IMG_HEIGHT);
   }

   public void clearScreen() {
      Graphics g = image.getGraphics();
      g.setColor(Color.black);
      g.fillRect(0, 0, image.getWidth(), image.getHeight());
      g.dispose();
      repaint();
   }

   private class MyMouseAdapter extends MouseAdapter {
      // code to draw on the buffered image. 
      // Don't forget to call repaint() on the "this" JPanel
   }
}
查看更多
登录 后发表回答