سؤال

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.

هل كانت مفيدة؟

المحلول

In that simple example, there's no need for try..finally; g2D.drawLine does not throw exceptions.1 However, if the body of the try might throw an exception, execute a return statement, or otherwise abnormally terminate the paint method, then I would recommend try..finally to ensure that the context is properly disposed.

1 It could, I suppose, throw an OutOfMemoryError or some other unchecked exception. If it does that, though, disposing of a Graphics2D context will be the least of your problems.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top