Java垃圾收集和图形处理方法 [英] Java Garbage Collection and Graphics dispose method
问题描述
我正在创建一款游戏(一个Snake Clone)作为一种爱好。我正在Java API的Graphics类中查看dispose方法。当我注释掉处理方法时,我的动画在有或没有它的情况下都可以正常工作。在Java API中,dispose方法执行此操作 - 释放图形上下文正在使用的系统资源。 Java垃圾收集不管理程序的内存类似于处理的内容吗?我应该保留处置方法吗?
API在解释同步方法方面没有太多帮助。但从我在其他论坛读到的内容来看,ToolKit类中的同步方法是为了确保绘图操作(如paintComponent方法,我猜想)会刷新显卡。所以,显卡的工作是清理程序以前的图形上下文的任何遗留物?
以下是代码:
public void paintComponent(Graphics g){
super.paintComponent(g);
Toolkit.getDefaultToolkit()。sync();
g.dispose();
来到 Graphics
有一个简单的原则。
如果您明确地创建它(例如 BuffereImage.createGraphics()
),则将其处理掉。
$ b $ < paintComponent(Graphics g)
实例 g
由工具包提供,并在需要时处理。在你自己的代码中这样做会导致'不可预知的'呈现。
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();
}
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.
这篇关于Java垃圾收集和图形处理方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!