Java - get Graphics

我的梦境 提交于 2019-12-13 02:50:26

问题


im making a java swing game. I heard that swing components don't use active rendering(you can only override paint methods), and for that reason, i have been using BufferStrategy with Canvas. Now i have discover the getGraphics() method from JComponent and JPanel. If we can do active render in swing components, why game tutorials still override paint() and paintComponent()?


回答1:


Don't EVER use getGraphics, it can return null and is nothing more the a snap-shot of the last paint cycle.

Anything you paint to it will be removed on the next paint cycle. In Swing you DON'T control the paint process and a paint cycle could be initiated for any number of reasons, many of which you don't have control over or would notified of (other then when paint was called)

The basic answer is, if you want control over the paint process, you MUST use a BufferStrategy or implement you own off screen drawing routines. There is NO means by which you can achieve a true active painting process within the Swing API, you can fake it to a certain extent, but Swing will still be able to perform it's own painting cycles when it sees fit.

Have a look at Painting in AWT and Swing and Performing Custom Painting for more details about how painting works in Swing



来源:https://stackoverflow.com/questions/28015214/java-get-graphics

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!