Null Pointer Exception on getGraphics()

时间秒杀一切 提交于 2019-11-28 00:26:56

You're likely trying to get the Graphics context via getGraphics() before the JPanel has been rendered, and thus the method returns null. Don't do this. There are problems with using getGraphics() on a component to get the Graphics context, one of which is the problem you're seeing above, and another is that the Graphics context obtained will not persist. There are occasions when this is necessary to do, but usually we do passive drawing via paintComponent(...). Often a Swing Timer can be used for the animation loop.

Jlewis071

I think it's because you're trying to draw using getGraphics() instead of the conventional override of paintComponent. You want to use something like this: drawImage is not drawing (see the top answer).

Sukhbir

getGraphics() method will return null if Component is not rendered till that statement and thus you will get NullPointerException, also if it is rendered Graphics will not be stable and better to use a paintComponents...

See link.

Also an Example "Better approach than getGraphics()"

the Component must first be visible try this before you start the thread in Game/panel

frame.add(panel) frame.setVisible(true)

then start the thread in Game/panel

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