Java - get Graphics

2019-09-10 07:45发布

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条回答
冷血范
2楼-- · 2019-09-10 08:28

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

查看更多
登录 后发表回答