swing - How to properly dispose graphics context - do I need try and finally? (Java 1.7) -
how dispose graphics context - need use try , finally? simple example:
public void paint(graphics g) { graphics2d g2d = (graphics2d) g.create(); try { g2d.drawline(0, 0, 10, 0); } { g2d.dispose(); } } edit
this example 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()); } } { gg.dispose(); } } super.paint(g); } as see, constructors used pretty simple, try , finally still exits. think practice use them.
in simple example, there's no need try..finally; g2d.drawline not throw exceptions.1 however, if body of try might throw exception, execute return statement, or otherwise abnormally terminate paint method, recommend try..finally ensure context disposed.
1 it could, suppose, throw outofmemoryerror or other unchecked exception. if that, though, disposing of graphics2d context least of problems.
Comments
Post a Comment