Error with timer and JFrame

后端 未结 3 1692
夕颜
夕颜 2021-01-29 13:36

I\'m making a game with a timer and a JFrame (and many other things but only these 2 are causing problems), and after running the segments below, I got a weird error. At least f

相关标签:
3条回答
  • 2021-01-29 14:12

    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?

    0 讨论(0)
  • 2021-01-29 14:32

    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.

    0 讨论(0)
  • 2021-01-29 14:32

    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.

    0 讨论(0)
提交回复
热议问题