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(){
            try{
                Thread.sleep(50);
            }
             catch(Exception e){ }
            repaint();
}
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(){
           
            while(true){
            try{
                  Thread.sleep(50);
            }catch(Exception ex){
                 
            }
            paint(this.getGraphics());
            }
      }
public void paint(Graphics g){
           
            animation(bf.getGraphics()); //bf is the BufferedImage object
            g.drawImage(bf,0,0,null);
      }

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(){
           
            while(true){
            try{
                  Thread.sleep(50);
            }catch(Exception ex){
                 
            }
              repaint();
            }
      }

public void update(Graphics g){
       paint(g);
}

public void paint(Graphics g){
           
            animation(bf.getGraphics()); //bf is the BufferedImage object
            g.drawImage(bf,0,0,null);
}

Download Files Here:


29 comments:

  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.getContentPane().add(mill);
    frame.setSize(new java.awt.Dimension(700,700));
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mill.setPreferredSize(new java.awt.Dimension(800,700));
    frame.setVisible(true);
    frame.pack();
    timer=new Timer(100,new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    t++;
    mill.repaint();
    }
    });
    timer.start();
    }
    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) {
    super.paintComponent(g);
    Graphics2D g3=(Graphics2D)g;
    {//.. paint only
    if( buff==null|| buff.getWidth()!=mill.getWidth() ||
    buff.getHeight()!=mill.getHeight()
    ){
    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);
    }
    }
    }

    ReplyDelete
  2. Awesome! Thanks a lot!

    ReplyDelete
  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: chk-ashok@hotmail.com

    ReplyDelete
  4. Hey,

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

    ReplyDelete
  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.

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

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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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: vientosdelnorte.nls.es

    ReplyDelete
  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

    ReplyDelete
  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 > www.sfgate.com

    ReplyDelete
  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: http://www.prweb.com/

    ReplyDelete
  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 ... http://www.mplindopleingroenenklein.nl/

    ReplyDelete
  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

    ReplyDelete
  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е - http://lovelounge.com.au/SantiagoLo
    My site :: Bestblog.Co

    ReplyDelete
  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 - http://platon.phvi.ch/index.php?title=Benutzer_Diskussion:MadelineCo
    my website :: cus-demo.sakura.ne.jp

    ReplyDelete
  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

    ReplyDelete
  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

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


    Mу web blоg; V2 Cigs Coupons

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


    my web pagе; Http://Www.Squidoo.com/

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


    my site flex Belt reviews

    ReplyDelete
  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
    here.

    Look іnto my weblog - http://www.holsteiner-arschloch.de/wiki/index.php?title=Benutzer:HolleyGTI

    ReplyDelete
  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 Www.365friendz.com

    ReplyDelete
  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 :: macarthurs.info

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


    Μy web page :: http://digi29.ugu.pl

    ReplyDelete
  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

    ReplyDelete