1

When overriding public void paintComponent(Graphics g) in any JComponent to perform custom painting of that JComponent, should the Graphic object g be disposed at the end of the painting (and why)?

public void paintComponent(Graphics g) {
    super.paintComponent(g);       
    g.drawString("To dispose or not to dispose ? ",10,20);
    //dispose or avoid ?
    g.dispose();  
}
c0der
  • 18,467
  • 6
  • 33
  • 65
  • 2
    Does this answer your question? [Why does calling dispose() on Graphics object cause JPanel to not render any components](https://stackoverflow.com/questions/13911743/why-does-calling-dispose-on-graphics-object-cause-jpanel-to-not-render-any-com) – isaace Aug 20 '21 at 15:13
  • @isaace "You only need to dispose of Graphics when you actually create it" in the [accepted answer](https://stackoverflow.com/a/13911783/3992939) does answer my question. It does not explain why you should refrain from disposing. – c0der Aug 20 '21 at 15:23

3 Answers3

2

You should not dispose of the Graphics object unless your code creates the Graphics object.

The paint() method of JComponent will create a Graphics object and pass it to the three painting methods of each component. See: A Closer Look at the Painting Mechanisn.

The paint() method will then dispose() of this temporary Graphics object when painting of the component is finished. Check out the code at: https://github.com/openjdk/jdk/blob/master/src/java.desktop/share/classes/javax/swing/JComponent.java

If you manually create a Graphics object then you should dispose it:

Graphics2D g2d = (Graphics2D)g.create();

// do custom painting

g2d.dispose();

Typically it is a good idea to create a copy of the passed Graphics object if you intend to alter the painting by adding an AffineTransform, for example, to the Graphics.

camickr
  • 321,443
  • 19
  • 166
  • 288
1

Generally, if you didn't create the resource, it's not your job to dispose of it. As that Graphics is being passed to you, I wouldn't worry about disposing of it.

Juan C Nuno
  • 476
  • 1
  • 3
  • 8
1

No do not dispose the Graphics object in paintComponent. This will prevent other Components from drawing.

The right way to use Graphics.dispose is when you are drawing to an image buffer, like

BufferedImage im = new BufferedImage(...,...);
Graphics g = im.getGraphics();
JPanel.paint(g); // for example
g.drawLine(...); // another example
g.dispose();
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80