Java AWT/Swing Graphics - why getGraphics() not possible as a field (instance variable)?

StackOverflow https://stackoverflow.com/questions/23174461

  •  06-07-2023
  •  | 
  •  

Frage

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?

War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top