How to properly dispose graphics context - do I need to use try
and finally
? Simple example:
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
try {
g2D.drawLine(0, 0, 10, 0);
} finally {
g2d.dispose();
}
}
EDIT
This is an example from java.awt.Window class:
/**
* {@inheritDoc}
*
* @since 1.7
*/
@Override
public void paint(Graphics g) {
if (!isOpaque()) {
Graphics gg = g.create();
try {
if (gg instanceof Graphics2D) {
gg.setColor(getBackground());
((Graphics2D)gg).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC));
gg.fillRect(0, 0, getWidth(), getHeight());
}
} finally {
gg.dispose();
}
}
super.paint(g);
}
As I see, constructors used are pretty simple, but try
and finally
still exits. So I think it would be a good practice to use them.