简体   繁体   中英

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

为什么在使getGraphics()为不同的MouseListener方法(mousedragged,mousereleased等)使用的实例变量时会得到NullPointerException,但是当你将getGraphics()保存为这些方法中的局部变量时,它可以正常工作吗?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM