Wednesday, June 18, 2008

The Flickering Problem

Flickering is a big problem which occurs while drawing on screen using Java.
Though its a big problem, there is a possibility that many people may not have been exposed to this menace.
Flickering occurs normally when drawing images one after another, and can also be seen in another form in case of Swing Components coming from nowhere in case of JLayeredPane coding.
While the origin of Flickering is given to the inability to repaint the screen by the JVM when needed, and more so because of the difficulty in understanding how the repaint calls actually work going from one component to another.
Sometimes its more good to know what can be done to avoid Flickering, than to know how Flickering happens.
The Flickering though not a correct term in case of JLayeredPane is a different case alltogether,
and is out of scope to discuss here.
So i intend to limit my discussion to basic Flickering occuring while drawing images on screen.
One method which is used heavily is to override the paintComponent method-------
public void paintComponent(Graphics g)
{ super.paintComponent(g);
g.drawImage(img,0,0,null);
}
in case you are painting an image referenced by "img" variable.
This way of code works very well for me.
Another thing which can be kept in mind while drawing images on screen is, draw the image on a JPanel...which you have to add to your JFrame.
Once you change the image, remove the JPanel from the JFrame and create a new JPanel with new image and add to your JFrame.....
And most importantly, dont forget to call pack() of your JFrame and repaint() method of your JPanel and JFrame.
These are the precautions which can be used to avoid Flickering but you may still see it somewhere.
As it depends also on the way you are displaying and handling your components, have a relook at your code , try to keep in mind the above precautions and yes, be prepared for some code tweaking and use of different approaches, as handling of Swing components is not all that easy,
but certainly not very difficult as well!!

No comments:

Post a Comment

Write Your Comments..

Share this Page:-