Results 1 to 4 of 4
- 07-06-2010, 03:18 AM #1
Member
- Join Date
- Jun 2010
- Posts
- 86
- Rep Power
- 0
do I need to dispose of my Graphics object?
I've got the following method. It takes in a BufferedImage, creates a Graphics object from it, uses that Graphics object to draw into the BufferedImage, and then returns.
Now, I've been told that the last thing I should do in a method like this is to add G.dispose(), but I thought that whatever is created in a method is local to that method only, and is therefore automatically released or destroyed at the end of the method.Java Code:public void draw(BufferedImage BI) { Graphics2D G = BI.createGraphics(); G.setColor(Color.BLUE); if (side == NORTH || side == SOUTH) G.drawRect(X, Y, LENGTH, THICKNESS); else G.drawRect(X, Y, THICKNESS, LENGTH); }
Is it important to explicitely dispose of the Graphics object at the end of the method.
-
Yes you should, you must dispose of the Graphics object here. Even though the variable goes out of scope, I don't think that the system resources that are used by the Graphics object are released unless you explicitly call dispose.
Note that on the other hand, should not dispose the Graphics object passed into a paintComponent override.
edit: good golly, as always, the API is a font of knowledge. Please have a look at the Graphics section and in particular the dispose method:
Disposes of this graphics context and releases any system resources that it is using. A Graphics object cannot be used after disposehas been called.
When a Java program runs, a large number of Graphics objects can be created within a short time frame. Although the finalization process of the garbage collector also disposes of the same system resources, it is preferable to manually free the associated resources by calling this method rather than to rely on a finalization process which may not run to completion for a long period of time.
Graphics objects which are provided as arguments to the paint and update methods of components are automatically released by the system when those methods return. For efficiency, programmers should call dispose when finished using a Graphics object only if it was created directly from a component or another Graphics object.Last edited by Fubarable; 07-06-2010 at 03:38 AM.
- 07-06-2010, 04:59 AM #3
Member
- Join Date
- Jun 2010
- Posts
- 86
- Rep Power
- 0
Thanks very much Fubarable.
-
Similar Threads
-
how to dispose?
By justlynn in forum NetBeansReplies: 15Last Post: 07-01-2010, 02:17 AM -
dispose()'ing a frame from itself.
By musasabi in forum New To JavaReplies: 12Last Post: 05-13-2010, 07:41 PM -
dispose
By simontkk2005 in forum AWT / SwingReplies: 3Last Post: 11-18-2009, 11:42 PM -
How to set line width in Graphics object?
By inc_123 in forum New To JavaReplies: 8Last Post: 08-15-2009, 10:34 PM -
dispose() does not work here
By arunkumarinfo in forum NetBeansReplies: 4Last Post: 02-01-2009, 12:16 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks