i\' m little bit confused about few things:
Example code,that shows my problem,this isn\'t compilable
// image
private Buf
is it good practice to do this
No, this is actually incredibly horrible and error prone. This assumes that this is the Component#getGraphics
method. The problem is Swing uses a passive rendering algorithm, that is, Swing decides when and what should be repainted and does this for optimisation reasons.
This means updates are not regular, which really helps when doing animation, and can happen at any time for any number reasons, many of which you simply don't and can't control.
For these reasons, painting should be done within one of the paint methods, preferably, paintComponent
of a JComponent
based class. This way, when Swing decides to do a repaint, one, you know about it and can update the output accordingly, and two, it won't clear what you have previously painted to it using getGraphics
which could cause flickering...
You are also running into potential threading issues, as you thread is trying to paint to the Graphics
context, so might the Event Dispatching Thread and that isn't going to end pretty...All painting should be done from within the context of the EDT (for component based painting)
You could try using a BufferedStrategy
, which would give you direct control over the painting process, but this limits you to the AWT library. Don't know if this is good or bad in your case.
one other thing, how graphic.dispose() works correctly? , because trying to remove this line of code, nothing happens.
dispose
basically releases any native resources that the Graphics
context might be holding. General rule of thumb, if you didn't create, you don't dispose of it.
So if you use Graphics#create
or BufferedImage#createGraphics
to obtain a Graphics
context, then you should call dispose
when your done with it.
On some systems calling dispose
on the Grpahics
context used to perform painting of components (such as that passed to paintComponent
or obtained from getGraphcis
) can prevent further content from been painted.
Equally, not disposing of Graphics
contexts that you have created can lead to memory leaks as they won't get garbage collected...