Reputation: 3
Why do you get a NullPointerException when making getGraphics() an instance variable which different MouseListener methods (mousedragged, mousereleased etc) use, but it works just fine when you save getGraphics() as a local variable inside those methods?
Upvotes: 0
Views: 99
Reputation: 324207
Why do you get a NullPointerException when making getGraphics() an instance variable
Probably because the Graphics object isn't initialized yet when you invoke the getGraphics() method because the frame is not yet visible.
In any case you should NOT use the getGraphics() method to obtain a Graphics object because any painting you do will only be temporary and will be lost the next time Swing determines a component needs to be repainted.
Custom painting should be done within the paintComponent()
method of your JPanel (or JComponent). Read the section from the Swing tutorial on Custom Painting for more information and examples.
Upvotes: 2