Home > Enterprise >  Swing custom painting: should `Graphic` object be disposed?
Swing custom painting: should `Graphic` object be disposed?

Time:09-17

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

CodePudding user response:

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.

CodePudding user response:

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.

CodePudding user response:

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();
  • Related