问题
I am creating a game (a Snake Clone) as a hobby. I was looking at the dispose method from the Graphics class in the Java API. When I comment out the dispose method, My animation works the same way just fine with or without it. In the Java API, the dispose method does this- releases system resources that the graphics context is using. Doesn't the Java garbage collection manage the memory of the program similar to what the dispose is doing? Should I keep the dispose method?
The API was not much help in explaining the sync method. But from what I read in other forums , the sync method from the ToolKit class is to ensure the drawing operation (like paintComponent method I suppose) flushes to the graphics card. So is the graphic card's job to clean up any remains of the previous graphics contexts of the program?
Here's the code:
public void paintComponent(Graphics g) {
super.paintComponent(g);
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
回答1:
When it comes to Graphics
there is a simple principle.
If you explicitly create it (e.g. BuffereImage.createGraphics()
) then dispose of it.
OTOH in paintComponent(Graphics g)
the instance g
is provided by the toolkit and disposed of when/if it needs to be. Doing so in your own code will cause 'unpredictable' rendering.
来源:https://stackoverflow.com/questions/14096836/java-garbage-collection-and-graphics-dispose-method