JPanel custom drawing using Graphics

后端 未结 1 406
悲哀的现实
悲哀的现实 2021-01-13 09:38

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() {
           


        
相关标签:
1条回答
  • 2021-01-13 10:10

    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
       }
    }
    
    0 讨论(0)
提交回复
热议问题