如何正确处理图形上下文 - 我最后需要尝试吗? (Java 1.7)

时间:2021-08-31 12:05:44

How to properly dispose graphics context - do I need to use try and finally? Simple example:

如何正确处理图形上下文 - 我需要使用try和finally吗?简单的例子:

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:

这是java.awt.Window类的一个例子:

     /**
     * {@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.

正如我所看到的,使用的构造函数非常简单,但尝试并最终仍然退出。所以我认为使用它们是一个好习惯。

1 个解决方案

#1


5  

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.

在这个简单的例子中,没有必要尝试..最终; g2D.drawLine不会抛出异常。但是,如果try的主体可能抛出异常,执行return语句,或者以其他方式异常终止paint方法,那么我建议try..finally以确保上下文正确处置。

1It 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.

1我想,它可以抛出OutOfMemoryError或其他一些未经检查的异常。但是,如果它这样做,处理Graphics2D上下文将是您遇到的最少问题。

#1


5  

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.

在这个简单的例子中,没有必要尝试..最终; g2D.drawLine不会抛出异常。但是,如果try的主体可能抛出异常,执行return语句,或者以其他方式异常终止paint方法,那么我建议try..finally以确保上下文正确处置。

1It 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.

1我想,它可以抛出OutOfMemoryError或其他一些未经检查的异常。但是,如果它这样做,处理Graphics2D上下文将是您遇到的最少问题。