我应该明确地处理 Graphics 对象吗?

smw*_*dia 4 java swing awt

javadoc 说:

为了提高效率,程序员应该在使用完 Graphics 对象后调用 dispose ,前提是它是直接从组件或另一个 Graphics 对象创建的。

那么在下面的代码中,我应该graphics.dispose()在返回之前调用吗?或者,我可以吗?

{  ...  
BufferedImage result = new BufferedImage(toWidth, toHeight, BufferedImage.TYPE_INT_RGB);  

java.awt.Graphics graphics=result.getGraphics();

graphics.drawImage(im.getScaledInstance(toWidth, toHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null);  

return result;  
}
Run Code Online (Sandbox Code Playgroud)

BufferedImage result返回和其他地方使用。

Mar*_*o13 5

Graphics对象可以被布置,并应地布置。

getGraphics呼叫BufferedImage在内部代表参加createGraphics,所以没有区别。该createGraphics调用最终委托给相应的GraphicsEnvironment实现,其中(对于SunGraphicsEnvironment)它创建了new一个SunGraphics2D.

最后,dispose方法SunGraphics2D说如下:

  /**
   * This object has no resources to dispose of per se, but the
   * doc comments for the base method in java.awt.Graphics imply
   * that this object will not be useable after it is disposed.
   * So, we sabotage the object to prevent further use to prevent
   * developers from relying on behavior that may not work on
   * other, less forgiving, VMs that really need to dispose of
   * resources.
   */
  public void dispose() {
      surfaceData = NullSurfaceData.theInstance;
      invalidatePipe();
  }
Run Code Online (Sandbox Code Playgroud)

这也给出了为什么确实应该被调用的理由(即使在默认实现中它不是绝对必要的)dispose