use super.paintComponent(g) or getGraphics() in java

后端 未结 2 2009
無奈伤痛
無奈伤痛 2021-01-14 23:55

i\' m little bit confused about few things:

Example code,that shows my problem,this isn\'t compilable

// image
private Buf         


        
2条回答
  •  北海茫月
    2021-01-15 00:22

    There are many questions about "good" or "correct" painting in Swing, so this question could be considered as a duplicate, and I won't try to repeat here what should be read in context, for example, in the Lesson about Performing Custom Painting.

    However, to summarize the most important information short and concisely:

    • You should never call getGraphics on a Component. It may return null or a Graphics object that is in any other way "invalid". It will fail in the one form or the other, sooner or later
    • You should do all your painting operations in the paintComponent method (or in methods that are called from paintComponent), using the Graphics object that you receive there as an argument
    • Whether or not you call the Graphics#dispose method may not make a difference that is "immediately" visible. You should not call it on the one that you received in the paintComponent. You should only call it on a Graphics object that you either obtained from a BufferedImage, or one that you created by calling Graphics#create(). When you do not call it, this might cause a memory leak that will only be noticed after the application has been running for a while.

提交回复
热议问题