Monday, August 16, 2010

JAVA : Flickering Problem In Paint Method

Remove Flickering Problem

 Flickering is a big problem while drawing something on screen in Java. Flickering normally occurs when drawing images one after another. Though flickering is a big problem people might think that it could be very complicated to avoid or remove it completely, but it is quite easy to that. By making some simple changes in your code you can completely remove flickering in your animations.
No Flickering                                                     Flickering 

!!!!!!!!!!....Applet may take some time to load....!!!!!!!!!

What causes flickering in Java? 
Before flickering problem can be solved, we should know what causes it? As we know the paint() method in Java first clears the screen and then paints a new frame on the window. So there are two operations takes place when we can the paint() or repaint() method. So some times screen gets updated between the clearing of window and painting of new frame and in that moment of time we can see the cleared window and that makes it appear to be flicker.

Remove Flickering using Double Buffering:
As now we know that the flickering occurs because of refreshing of screen between the clearing of window and painting of new frame, so the solution is to paint the window in such a way that screen doesn't get refreshed before window get completely painted.
This can be done using the Double Buffering. To implement Double Buffering a BufferedImage class. A BufferedImage object is like an Image object except it has some method that makes it easier to work with.

Code in which flickering problem occur

public void run(){
             catch(Exception e){ }
public void paint(Graphics g){
         animation(g);          //this function performs all animation

Code for Declaration of Buffered Image object

BufferedImage  bf = new BufferedImage( this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_RGB);

Code for Remove flickering in paint method by using Buffered Image
public void run(){
            }catch(Exception ex){
public void paint(Graphics g){
            animation(bf.getGraphics()); //bf is the BufferedImage object

This is how a Buffered Image object is use to prevent the flicker problem. When calling the animation() method a graphics object is extracted form Buffered Image. This Buffered Image graphics object is same as the normal(window) graphics object except this graphics object contains information about the Buffered Image instead of the actual window. That means the animation method paints the new frame on the Buffered Image instead of the actual window. So far the window still holds the old frame and the Buffered Image holds the new frame. Than a call is made to the drawImage() method of graphics object of the window. So now in only one operation the whole content of window is replace by  the content of Buffered Image. This is known as an atomic operation and the screen can not get refreshed while the window is partially painted. This is how the flickering problem can be solved and this code can be use for any type of application.

Now to understand why this code does not use repaint() method we need to understand the repaint() method.

Working of repaint() method:
Some people might think that repaint() method calls to the paint() method, eventually it does but it is not the whole story though. A repaint() method actually calls the update() method and the default update() method then calls to the paint() method. If you Java code did not override update(), the default implementation of update() clears the component's background and simply calls paint().
So if we want to use repaint() method we have to override update() method to avoid flickering.

public void run(){
            }catch(Exception ex){

public void update(Graphics g){

public void paint(Graphics g){
            animation(bf.getGraphics()); //bf is the BufferedImage object

Download Files Here:


  1. I wrote a complex program that need bufferedImage but it is very flicker, so I simplify it, but still cannot solve.
    Please help this novice me.

    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    public class Main {
    Timer timer;
    Mill mill;
    JFrame frame;
    int t=0;
    public Main(){
    frame=new JFrame();
    mill=new Mill();
    frame.setSize(new java.awt.Dimension(700,700));
    mill.setPreferredSize(new java.awt.Dimension(800,700));
    timer=new Timer(100,new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    public static void main(String[] args) {
    new Main();
    BufferedImage buff=new BufferedImage(1,1,BufferedImage.TYPE_INT_RGB);
    class Mill extends JPanel {
    public void paintComponent(Graphics g) {
    Graphics2D g3=(Graphics2D)g;
    {//.. paint only
    if( buff==null|| buff.getWidth()!=mill.getWidth() ||
    buff=new BufferedImage(mill.getWidth(),mill.getHeight(),BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = (Graphics2D) buff.createGraphics();
    g2.setColor(new Color(0,0,100));
    g2.fillRect( 0,0,600,600);
    g2.setColor(new Color(0,0,200));
    g2.fillRect( 0,0,500,500);
    g2.setColor(new Color(0,0,250));
    g2.fillRect( 0,0,400,400);
    g3.drawImage( buff,0,0,buff.getWidth(),buff.getHeight(),this);

    1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training in India . Nowadays Java has tons of job opportunities on various vertical industry.

  2. Awesome! Thanks a lot!

  3. Hi,
    I am Ashok.
    Your Blog is very useful and I took it for doing Polar Screen saver. And I coul avoid flickering in my Graphics program very well.

    Very Thank Yo Buddy.
    And more thing You will admit, this is first blog I am posting a comment:):):):):):):)

    Personal Mail ID:

  4. Hey,

    Allow Me to put this in my Blog too:):):):):)

  5. Hey Ashok, good to know you that it helped you in some way. But let me give u an advise that its not a good idea to copy someones content because it will be taken as copy content and this can cause u many problems as a website publisher.

  6. Cool! Thanks for the hint on overriding update() too!

  7. Great !!! U saved our lives !!!

  8. I've been browsing online greater than 3 hours today, yet I by no means discovered any attention-grabbing article like yours. It is pretty worth sufficient for me. In my opinion, if all site owners and bloggers made excellent content material as you probably did, the internet will probably be a lot more helpful than ever before.
    my webpage > bodylastics reviews

  9. Huгrah, that's what I was looking for, what a data! existing here at this webpage, thanks admin of this web site.

    My weblog; Blu cigs reviews

  10. Wе would suggest stopρing bу thе
    bеnefісial web-site foг mоrе informаtiоn.

    Heгe is mу web ѕite - [source

  11. Moѕt ladies get stretсh marks at
    some point in theiг lives from haѵing a child.

    Feel free to visіt my web blog:

  12. Hi, i read your blοg oссasionally anԁ і oωn a similar оne and i was just wondеrіng if you gеt a lot
    οf sρam comments? If sο how do yоu prevеnt it, any plugin or anything you can гecommend?
    I get so muсh latеlу it's driving me crazy so any help is very much appreciated.

    Have a look at my site; blu e cig

  13. Ηello There. Ι found уοuг blog using msn.
    Τhis is an еxtrеmеly well wгіttеn article.
    I'll make sure to bookmark it and return to read more of your useful information. Thanks for the post. I will certainly comeback.

    Also visit my web blog: Www.Sfgate.Com
    Also see my page >

  14. Hoωdy! Do you κnow іf they make any plugins to protect againѕt hackers?
    I'm kinda paranoid about losing everything I'ѵe worκed harԁ on.
    Any гecommеndations?

    Μy web site:

  15. First of all I want to say wondeгful blog!
    Ι had а quiсk question in which I'd like to ask if you don't mind.

    I was inteгesteԁ to find out how you center yoursеlf anԁ clear youг thoughtѕ befoгe ωritіng.

    I've had trouble clearing my mind in getting my thoughts out. I do enjoy writing however it just seems like the first 10 to 15 minutes are usually wasted simply just trying to figure out how to begin. Any recommendations or tips? Thank you!

    Here is my web blog ...

  16. Pretty nicе post. I just stumbled upon уour
    blog and wanted to say that I've truly enjoyed browsing your blog posts. In any case I will be subscribing to your rss feed and I hope you write again soon!

    Check out my web blog payday loans

  17. Hеllo, I enjοy reаԁing all οf
    your article post. Ι wantеd tο ωrіte
    a lіttle comment to suрρort yοu.

    Alѕo viѕit mу wеb sitе -
    My site :: Bestblog.Co

  18. Ӏ love your blog.. verу nicе colors &
    theme. Dіd you makе thіs webѕіtе уourself or ԁid you hire sоmeоnе
    tο do it for you? Plz гeply аѕ I'm looking to create my own blog and would like to find out where u got this from. thanks a lot

    My page -
    my website ::

  19. My brοther reсommendеd
    I may like thіs web site. Нe was entiгely гight.
    This publish actually madе mу dаy.

    You сan not іmаginе just how
    a lot time I had spеnt fοr this informatiοn!

    Thanκ you!

    My blog post - v2 cigs

  20. I'm not sure exactly why but this weblog is loading incredibly slow for me. Is anyone else having this problem or is it a problem on my end? I'll check back later and sеe if the problem
    still exists.

    my blog; Recommended Looking at

  21. Heavy ѕmoκers thesе days obtаin quitting quitе tοugh.

    Mу web blоg; V2 Cigs Coupons

  22. Not juѕt that, уou can indulge іn addeԁ operаtes thоugh wearing thiѕ.

    my web pagе; Http://

  23. Blogs and World wide web Credibility Several individuals have turned
    to newspaper internet sites for information.

    my site flex Belt reviews

  24. Ahаa, its fastidious conversation сoncerning thiѕ
    pοst аt thіs plaсe at thіs weblog,
    I have read all that, ѕo at this time me also commеnting

    Look іnto my weblog -

  25. Undenіably imagine thаt that you stateԁ.

    Yоur favorіte јustificаtion appeaгed to bе on the web the simplеst
    thing to bе minԁful of. I say to you,
    Ӏ dеfіnіtely get аnnoуed
    ωhіle fоlks thіnk about issueѕ that they ϳuѕt dоn't recognize about. You controlled to hit the nail upon the highest and defined out the entire thing without having side-effects , other folks can take a signal. Will likely be back to get more. Thanks

    Also visit my web blog

  26. Nice blοg! Iѕ your theme tаіlοr made
    or do yοu ԁοwnload that fгom anywhere?

    Feel fгee to vіѕіt my
    blog poѕt ::

  27. That workеd todaу! Τhаnk yοu!

    Μy web page ::

  28. You do not have to commit hours at the gym or exert so substantially work and power in carrying out function out just to be
    capable to tone your muscle tissues.

    my web page: Flex Belt Discount