javaswinggraphicscustom-painting

Swing custom painting: should `Graphic` object be disposed?


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();  
}

Solution

  • 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.