Error with timer and JFrame

半城伤御伤魂 提交于 2019-12-02 13:32:11

You get NPE because you are passing null as graphics in window.paintComponents(null); And then you are calling g.drawImage(j.getImage(),j.getX(), j.getY(), null); where g is null.

You shouldn't be painting direclty in a JFrame at all but rather a JPanel or JComponent that is held by the JFrame. You should override the JPanel's paintComponent method as noted above (not the JFrame since it doesn't even have this method) and paint in there. Another thing, don't use a java.util.Timer but rather a javax.swing.Timer better known as a Swing Timer since this is a Swing application. Also you shouldn't call paint/paintComponent directly but rather have your GUI update class fields then call repaint() on the JPanel that you're doing your drawing on and then paintComponent will (usually) be called by the JVM. There are many examples of Swing animation here in this forum and I suggest you search out these examples and learn from them as I think that they can help you.

Edit: heck, you've already been told all of this in your previous threads. Why should we help you if you ignore our advice?

camickr

The method to override is paintComponent() not "paintComponents" (with an s).

You should never invoke the paintComponent() method directly. Instead you invoke the repaint() method on the component.

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