Double buffering && repaint

Hi there,
I have a frame F that contains two panels P1 and P2.
P1 uses double buffering for drawing circles and lines.
P2 has buttons and a JList.
When i click on a JList to have popup menu
or when i move the frame F on the screen
the panel P2 lost some of JList drawing.
Actually i iconify the frame in order to oblige
JVM to do repaint.
How can i resolve this problem please.

Do not ever mix heavyweight and lightweight, or else
you won't be able to set up the correct zorder.But when i iconfiy and desiconify my frame Java
repaint correctly.
I need a nice tip article of how to simulate
desiconify repainting process.
Thabk u

Similar Messages

  • Printing JTable after turning off double buffering causing repaint problems

    I've followed all the instructions to speed up a print job in java by turning off double buffering temporarily by using the following call before calling paint() on the component...
    RepaintManager.currentManager(printTable).setDoubleBufferingEnabled(false);
    ... and then turning it back on afterwards...
    RepaintManager.currentManager(printTable).setDoubleBufferingEnabled(true);
    but the problem is that if it is a long print job, then the rest of the application (including other JTables) isn't repainting properly at all. I have the printing going on in a separate thread since I don't think it's acceptable UI practices to force the user to wait until a print job finishes before they can proceed with using their application. I've tried controlling the double buffering at the JPanel level as well, but it always affects the entire application until the print spooling is complete.
    Does anyone have any suggestions to solve this annoying SWING printing problem?
    Thanks,
    - Tony

    When you post code, make sure and put it between code
    tags, so it looks good:
    public static void main(String[] args) {
    System.out.println("Doesn't this look great?");
        public int print(Graphics g, PageFormat pf, int pageIndex) {
            System.out.println( "Calling print(g,pf,pageIndex) method" );
            int response = NO_SUCH_PAGE;
            Graphics2D g2 = (Graphics2D) g;
    // for faster printing, turn off double buffering
            disableDoubleBuffering(componentToBePrinted);
            Dimension d = componentToBePrinted.getSize(); //get size of document
            double panelWidth = d.width; //width in pixels
            double panelHeight = d.height; //height in pixels
            double pageHeight = pf.getImageableHeight(); //height of printer page
            double pageWidth = pf.getImageableWidth(); //width of printer page
            double scale = pageWidth / panelWidth;
            int totalNumPages = (int) Math.ceil(scale * panelHeight / pageHeight);
    // make sure not print empty pages
            if (pageIndex >= totalNumPages) {
                response = NO_SUCH_PAGE;
            } else {
    // shift Graphic to line up with beginning of print-imageable region
                g2.translate(pf.getImageableX(), pf.getImageableY());
    // shift Graphic to line up with beginning of next page to print
                g2.translate(0f, -pageIndex * pageHeight);
    // scale the page so the width fits...
                g2.scale(scale, scale);
                componentToBePrinted.paint(g2); //repaint the page for printing
                enableDoubleBuffering(componentToBePrinted);
                response = Printable.PAGE_EXISTS;
            return response;
        }

  • Problem with Double Buffering and Swing

    Hi
    I made a game and basically it works pretty well, my only problem is it flickers really badly right now. I read up on a whole lot of forums about double buffering and none of those methods seemed to work. Then I noticed that Swing has double buffering built in so I tried that but then I get compilation errors and I'm really not sure why. My original code was a console application and worked perfectly, then I ported it into a JApplet and it still works but it flickers and thats what I'm tryign to fix now.
    The code below is in my main class under the constructor.
    Heres the double buffering code I'm trying to use, I'm sure you all seen it before lol
    public void update(Graphics g)
              // initialize buffer
              if (dbImage == null)
                   dbImage = createImage(this.getSize().width, this.getSize().height);
                   dbg = dbImage.getGraphics();
              // clear screen in background
              dbg.setColor(getBackground());
              dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
              // draw elements in background
              dbg.setColor(getForeground());
              paint(dbg);
              // draw image on the screen
              g.drawImage(dbImage, 0, 0, this);
         }My paint is right under neath and heres how it looks
    This snipet of code works but when I change the method to
    public paintComponent(Graphics g){
    super.paintComponent(g)...
    everythign stops working and get a compilation error and says that it can't find paintComponent in javax.swing.JFrame.
    public void paint(Graphics g)
              super.paint(g);
              //if game starting display menue
              if (show_menue)
                   //to restart lives if player dies
                   lives = 3;
                   menue.draw_menue(g);
                   menue_ufo1.draw_shape(g);
                   menue_ufo2.shape_color = Color.DARK_GRAY;
                   menue_ufo2.draw_shape(g);
                   menue_ufo3.shape_color = Color.BLUE;
                   menue_ufo3.draw_shape(g);
                   menue_ufo4.shape_color = new Color(82, 157, 22);
                   menue_ufo4.draw_shape(g);
                   menue_ufo5.draw_shape(g);
                   menue_ufo6.shape_color = new Color(130, 3, 3); ;
                   menue_ufo6.draw_shape(g);
                   menue_turret.draw_ship(g);
                   menue_ammo.draw_ammo(g);
              else
                   //otherwise redraw game objects
                   gunner.draw_ship(g);
                   y_ammo.draw_ammo(g);
                   grass.draw_bar(g);
                   o_ufo.draw_shape(g);
                   b_ufo.draw_shape(g);
                   m_ufo.draw_shape(g);
                   s_ufo.draw_shape(g);
                   z_ufo.draw_shape(g);
                   xx_ufo.draw_shape(g);
                   info.draw_bar(g);
                   live_painter.draw_lives(g, lives);
                   score_painter.draw_score(g, score);
                   level_display.draw_level(g, level);
                   explosion.draw_boom(g);
         }I just want to get rid of the flickering for now so any help will be greatly appreciated. Depending which will be simpler I can either try to double buffer this program or port it all to swing but I'm not sure which elements are effected by AWT and which by Swing. Also I read some of the Java documentation but couldn't really understand how to implement it to fix my program.
    Thanks in advance
    Sebastian

    This is a simple animation example quickly thrown together. I have two classes, an animation panel which is a JPanel subclass that overrides paintComponent and draws the animation, and a JApplet subclass that simply holds the animation panel in the applet's contentpane:
    SimpleAnimationPanel.java
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Point;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.imageio.ImageIO;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    class SimpleAnimationPanel extends JPanel
        private static final int DELAY = 20;
        public static final int X_TRANSLATION = 2;
        public static final int Y_TRANSLATION = 2;
        private Point point = new Point(5, 32);
        private BufferedImage duke = null;
        private Timer timer = new Timer(DELAY, new TimerAction());
        public SimpleAnimationPanel()
            try
                // borrow an image from sun.com
                duke = ImageIO.read(new URL(
                        "http://java.sun.com/products/plugin/images/duke.wave.med.gif"));
            catch (MalformedURLException e)
                e.printStackTrace();
            catch (IOException e)
                e.printStackTrace();
            setPreferredSize(new Dimension(600, 400));
            timer.start();
        // do our drawing here in the paintComponent override
        @Override
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            if (duke != null)
                g.drawImage(duke, point.x, point.y, this);
        private class TimerAction implements ActionListener
            @Override
            public void actionPerformed(ActionEvent e)
                int x = point.x;
                int y = point.y;
                Dimension size = SimpleAnimationPanel.this.getSize();
                if (x > size.width)
                    x = 0;
                else
                    x += X_TRANSLATION;
                if (y > size.height)
                    y = 0;
                else
                    y += Y_TRANSLATION;
                point.setLocation(new Point(x, y)); // update the point
                SimpleAnimationPanel.this.repaint();
    }AnimationApplet.java
    import java.lang.reflect.InvocationTargetException;
    import javax.swing.JApplet;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    public class AnimationApplet extends JApplet
        public void init()
            try
                SwingUtilities.invokeAndWait(new Runnable()
                    public void run()
                        // construct the panel
                        JPanel simpleAnimation = new SimpleAnimationPanel();
                        // put it in the contentPane of the JApplet
                        getContentPane().add(simpleAnimation);
                        setSize(simpleAnimation.getPreferredSize());
            catch (InterruptedException e)
                e.printStackTrace();
            catch (InvocationTargetException e)
                e.printStackTrace();
    }Here's a 3rd bonus class that shows how to put the JPanel into a stand-alone program, a JFrame. It's very similar to doing it in the JApplet:
    AnimationFrame.java
    import javax.swing.JFrame;
    public class AnimationFrame
        private static void createAndShowUI()
            JFrame frame = new JFrame("SimpleAnimationPanel");
            frame.getContentPane().add(new SimpleAnimationPanel());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        public static void main(String[] args)
            java.awt.EventQueue.invokeLater(new Runnable()
                public void run()
                    createAndShowUI();
    }Edited by: Encephalopathic on Mar 15, 2008 11:01 PM

  • Alternative to Double-Buffered Canvas

    I am working on a program in which I use a double-buffered Canvas inside a JScrollPane. The problem is that the Canvas draws over the scrollbars. I have tried extending JComponent, JPanel, JApplet, and Component instead of Canvas, and none of them are double buffered. Here is the code I used to debug this problem:
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class Test implements  Runnable
         JFrame f;
         JScrollPane scroller;
         JPanel panel;
         TestCanvas canvas;
         Thread runner;
         BufferStrategy strategy;
         public static void main (String[] args) {
              Test app = new Test();
              app.init();
         public void init() {
              f = new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              panel = new JPanel();
              canvas = new TestCanvas();
              panel.add(canvas);
              scroller = new JScrollPane(panel);
              scroller.setWheelScrollingEnabled(true);
              f.getContentPane().add(scroller);
              f.pack();
              f.setSize(300,300);
              f.setVisible(true);
              canvas.createBufferStrategy(2);
              strategy = canvas.getBufferStrategy();
              runner = new Thread(this);
              runner.run();
         public void run() {
              int x = 0;
              while(x != 65536) {
                   Graphics2D g = (Graphics2D)strategy.getDrawGraphics().create();
                   g.setColor(new Color(x%256,0,0));
                   g.fill(new Ellipse2D.Double(0,0,600,600));
                   strategy.show();
                   x++;
    }Any suggestions?

    The main culprit is that you are mixing AWT components with Swing ones.
    In addition, your are doing so many of useless things and wrong things in your code.
    Swing components are defaulted for using double-buffering.
    See: http://java.sun.com/products/jfc/tsc/articles/painting/index.html
    Try and study this code.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class Fox1229{
      JFrame f;
      JScrollPane scroller;
      TestCanvas canvas;
      int x;
      Timer t;
      public static void main (String[] args) {
        Fox1229 app = new Fox1229();
        app.init();
      public void init() {
        x = 0;
        f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        canvas = new TestCanvas();
        scroller = new JScrollPane(canvas);
        scroller.setWheelScrollingEnabled(true);
        f.getContentPane().add(scroller, BorderLayout.CENTER);
        f.setSize(300, 300);
        f.setVisible(true);
        t = new Timer(50, new ActionListener(){
          public void actionPerformed(ActionEvent e){
            canvas.setOc(new Color(x % 256, 0, 0));
            canvas.repaint();
            if (++x == 1024){
              t.stop();
        t.start();
    class TestCanvas extends JPanel{
      Color oc;
      public TestCanvas (){
        oc = new Color(0, 0, 0);
      public void setOc(Color c){
        oc = c;
      public Dimension getPreferredSize(){
        return new Dimension(600, 600);
      public void paintComponent(Graphics g){
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D)g;
        g2d.setColor(Color.blue);
        g2d.fill(new Rectangle(0, 0, 600, 600));
        g2d.setColor(oc);
        g2d.fill(new Ellipse2D.Double(0, 0, 600, 600));
    }

  • Double buffering still gives flickering graphics.

    I copied code from a tutorail which is supposed to illustrate double buffering.
    After I run it, it still flickers though.
    I use applet viewer, which is part of netbeans to run my applet.
    Link to tutorial: http://www.javacooperation.gmxhome.de/TutorialStartEng.html
    My questions are:
    Is the strategy used for double buffering correct?
    Why does it flicker?
    Why does the program change the priority a couple of times?
    Can you make fast games in JApplets or is there a better way to make games? (I think C++ is too hard)
    Here is the code:
    package ballspel;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Image;
    import javax.swing.JApplet;
    //import java.applet.*;
    * @author Somelauw
    public class BallApplet extends /*Applet*/ JApplet implements Runnable {
    private Image dbImage;
    private Graphics dbg;
    private int radius = 20;
    private int xPos = 10;
    private int yPos = 100;
    * Initialization method that will be called after the applet is loaded
    * into the browser.
    @Override
    public void init() {
    //System.out.println(this.isDoubleBuffered()); //returns false
    // Isn't there a builtin way to force double buffering?
    // TODO start asynchronous download of heavy resources
    @Override
    public void start() {
    Thread th = new Thread(this);
    th.start();
    public void run() {
    Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
    while (true) {
    xPos++;
    repaint();
    try {
    Thread.sleep(20);
    } catch (InterruptedException ex) {
    ex.printStackTrace();
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    @Override
    public void paint(Graphics g) {
    super.paint(g);
    //g.clear();//, yPos, WIDTH, WIDTH)
    g.setColor(Color.red);
    g.fillOval(xPos - radius, yPos - radius, 2 * radius, 2 * radius);
    @Override
    public void update(Graphics g) {
    super.update(g);
    // initialize buffer
    if (dbImage == null) {
    dbImage = createImage(this.getSize().width, this.getSize().height);
    dbg = dbImage.getGraphics();
    // clear screen in background
    dbg.setColor(getBackground());
    dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
    // draw elements in background
    dbg.setColor(getForeground());
    paint(dbg);
    // draw image on the screen
    g.drawImage(dbImage, 0, 0, this);
    // TODO overwrite start(), stop() and destroy() methods
    }

    Somelauw wrote:
    I copied code from a tutorail which is supposed to illustrate double buffering.
    After I run it, it still flickers though.
    I use applet viewer, which is part of netbeans.. AppletViewer is part of the JDK, not NetBeans.
    ..to run my applet.
    Link to tutorial: http://www.javacooperation.gmxhome.de/TutorialStartEng.html
    Did you specifically mean the code mentioned on this page?
    [http://www.javacooperation.gmxhome.de/BildschirmflackernEng.html]
    Don't expect people to go hunting around the site, looking for the code you happen to be referring to.
    As an aside, please use the code tags when posting code, code snippets, XML/HTML or input/output. The code tags help retain the formatting and indentation of the sample. To use the code tags, select the sample and click the CODE button.
    Here is the code you posted, as it appears in code tags.
    package ballspel;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Image;
    import javax.swing.JApplet;
    //import java.applet.*;
    * @author Somelauw
    public class BallApplet extends /*Applet*/ JApplet implements Runnable {
        private Image dbImage;
        private Graphics dbg;
        private int radius = 20;
        private int xPos = 10;
        private int yPos = 100;
         * Initialization method that will be called after the applet is loaded
         * into the browser.
        @Override
        public void init() {
            //System.out.println(this.isDoubleBuffered()); //returns false
            // Isn't there a builtin way to force double buffering?
            // TODO start asynchronous download of heavy resources
        @Override
        public void start() {
            Thread th = new Thread(this);
            th.start();
        public void run() {
            Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
            while (true) {
                xPos++;
                repaint();
                try {
                    Thread.sleep(20);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
        @Override
        public void paint(Graphics g) {
            super.paint(g);
            //g.clear();//, yPos, WIDTH, WIDTH)
            g.setColor(Color.red);
            g.fillOval(xPos - radius, yPos - radius, 2 * radius, 2 * radius);
        @Override
        public void update(Graphics g) {
            super.update(g);
            // initialize buffer
            if (dbImage == null) {
                dbImage = createImage(this.getSize().width, this.getSize().height);
                dbg = dbImage.getGraphics();
            // clear screen in background
            dbg.setColor(getBackground());
            dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
            // draw elements in background
            dbg.setColor(getForeground());
            paint(dbg);
            // draw image on the screen
            g.drawImage(dbImage, 0, 0, this);
        // TODO overwrite start(), stop() and destroy() methods
    }Edit 1:
    - For animation code, it would be typical to use a javax.swing.Timer for triggering updates, rather than implementing Runnable (etc.)
    - Attempting to set the thread priority will throw a SecurityException, though oddly it occurs when attempting to set the Thread priority to maximum, whereas the earlier call to set the Thread priority to minimum passed without comment (exception).
    - The paint() method of that applet is not double buffered.
    - It is generally advisable to override paintComponent(Graphics) in a JPanel that is added to the top-level applet (or JFrame, or JWindow, or JDialog..) rather than the paint(Graphics) method of the top-level container itself.
    Edited by: AndrewThompson64 on Jan 22, 2010 12:47 PM

  • Double Buffering +MVC

    been trying to implement double buffering but to no avail, have read a lot of articles online about implementing double buffering which seems relitivly straight forward and code that I developed matches what they have; the only problem that I have is that it is not calling update(graphics g) to get it to repaint, but instead calls update(Observable arg0, Object arg1) which I use for my mvc implementation. I've been toiling wiht this for days and not getting anywhere with it.
    Any Ideas - on how this could be resolved??
    TIA

    i'm using swing, Then your question should be posted in the Swing forum.
    but doesn't call the update method that I have overriddenI don't know why you are overriding update(). If you want a component to repaint itself then you use the repaint() method.
    This posting, from the Swing forum, has a couple examples of animation.

  • Double buffering method - confusion

    Hello everyone,
    I've been messing around with Applets and animation in them and needed a method to reduce/remove flicker, so I decided on double buffering and looked up a tutorial on it. I understand the concept of it clearly, however the code doesn't make too much sense to me even after reading paint/graphics pages. What confuses me is:
    Why is the "g.drawString()" in update method if it already paints the dbg graphics? I commented it out, and the ball won't move. In addition, in the drawImage method it draws dbImage which is only altered once (see when it was null), so how are we using it to double buffer if we never write to it except once?
    import java.applet.*;
    import java.awt.*;
    public class BallBasic extends Applet implements Runnable {
        int x_pos = 10;
        int y_pos = 10;
        int radius = 20;
        private Image dbImage;
        private Graphics dbg;
        public void init() {
            setBackground(Color.blue);
        public void start() {
            Thread th = new Thread(this);
            th.start();
        public void stop() {
        public void destroy() {
        public void run() {
            Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
            while (true) {
                x_pos++;
                repaint();
                try {
                    Thread.sleep(20);
                } catch (InterruptedException ex) {
                Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
        public void update(Graphics g) {
            if (dbImage == null) {
                System.out.println("dbImage was null");
                dbImage = createImage(this.getSize().width, this.getSize().height);
                dbg = dbImage.getGraphics();
            dbg.setColor(getBackground());
            dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
            dbg.setColor(getForeground());
            paint(dbg);
            g.drawImage(dbImage, 0, 0, this);
        public void paint(Graphics g) {
            g.setColor(Color.red);
            g.fillOval(x_pos - radius, y_pos - radius, 2 * radius, 2 * radius);
    }Thanks for reading, hope you can help.
    Note: I understand how the panting process works, how it ties into update, ectcetera, please do not post explanations of how painting/applets work, just looking for heavy comments on what is happening throughout the update/paint method.

    Patrick_Ritchie wrote:
    I want to understand the concepts of this and how to use just plain ol' applets. I need to learn these things ;)Most people skip the old AWT. Did you learn how steam engines worked before you learned to drive a car?

  • Which is better, Double Buffering 1, or Double Buffering 2??

    Hi,
    I came across a book that uses a completely different approach to double buffering. I use this method:
    private Graphics dbg;
    private Image dbImage;
    public void update() {
      if (dbImage == null) {
        dbImage = createImage(this.getSize().width, this.getSize().height);
        dbg = dbImage.getGraphics();
      dbg.setColor(this.getBackground());
      dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
      dbg.setColor(this.getForeground());
      paint(dbg);
      g.drawImage(dbImage, 0, 0, this);
    }that was my method for double buffering, and this is the books method:
    import java.awt.*;
    public class DB extends Canvas {
         private Image[] backing = new Image[2];
         private int imageToDraw = 0;
         private int imageNotDraw = 1;
         public void update(Graphics g) {
              paint(g);
         public synchronized void paint(Graphics g) {
              g.drawImage(backing[imageToDraw], 0, 0, this);
         public void addNotify() {
              super.addNotify();
              backing[0] = createImage(400, 400);
              backing[1] = createImage(400, 400);
              setSize(400, 400);
              new Thread(
                   new Runnable() {
                        private int direction = 1;
                        private int position = 0;
                        public void run() {
                             while (true) {
                                  try {
                                       Thread.sleep(10);
                                  }catch (InterruptedException ex) {
                                  Graphics g = backing[imageNotDraw].getGraphics();
                                  g.clearRect(0, 0, 400, 400);
                                                    g.setColor(Color.black);
                                  g.drawOval(position, 200 - position, 400 - (2 * position), 72 * position);
                                  synchronized (DB.this) {
                                       int temp = imageNotDraw;
                                       imageNotDraw = imageToDraw;
                                       imageToDraw = temp;
                                  position += direction;
                                  if (position > 199) {
                                       direction = -1;
                                  }else if (position < 1) {
                                       direction = 1;
                                  repaint();
              ).start();
         public static void main(String args[]) {
              Frame f = new Frame("Double Buffering");
              f.add(new DB(), BorderLayout.CENTER);
              f.pack();
              f.show();
    }which is better? I noticed smoother animation with the later method.
    Is there no difference? Or is it just a figment of my imagination??

    To be fair if you download an applet all the class files are stored in your .jpi_cache, and depending on how that game requests its graphics sometimes they are stored there to, so really if you have to download an applet game twice, blame the programmer (I've probably got that dead wrong :B ).
    But, what's wrong with Jars. They offer so much more.
    No offence meant by this Malohkan but if you can't organize your downloaded files the internet must really be a landmine for you :)
    Personally I'd be happy if I never seen another applet again, it seems java is tied to this legacy, and to the average computer user it seems that is all java is capable of.
    Admitidly there are some very funky applets out here using lots of way over my head funky pixel tricks, but they would look so much better running full screen and offline.

  • Flickering vs double buffering

    Hello,
    flickering is a common problem and is prevented by using offscreen images. And that's what I'm doing (though, I'm not sure whether I'm doing it right). Now, there's a cycle of images displayed as an animation in my program and the flickering is really obvious while the first cycle is being displayed. It seems more or less OK when it plays further (I'm not realy sure whether it flickers or not, coz the images are being repainted rather fast).
    So, my question is: why exactly could the first cycle be displayed so slowly and how could I fix the problem? (perhaps double buffering should fix it and I'm doing it wrong?)

    Are you loading all images before showing the animations ? Because if you are loading them as you're showing the animations the loading process will slow your animation down.

  • Strange double buffering bug

    Hi all,
    I have stumbled on strange swing behavior on Windows, most probably connected to double buffering introduced in java 6.
    Once in a while Windows stops redrawing my JFrame. From the java side everything seems ok - all the components are painted (that is, all native methods called), EventQueue normally processed by EDT, but repainted GUI is not shown on the screen. Note that OS has the repainted info - if I cover part of the application window with another window (e.g. explorer), and hid it back, the part that was covered is repainted. This happens even if I have java app halted on debug, so no other java actions can cause this repaint - OS has to have this image, it just does not put it on the screen. When I minimize/maximize the app, everything goes back to normal.
    Note that I can normally operate the app "as if" it was painted - I can change tabs, click buttons (even though I can't see them), and results of these actions are painted by java to some offscreen buffer, but are only shown when I cover/uncover my app with another window, or min/max it. Min/Maxing ends this strange state and further repaints are shown normally.
    Did any of you have this kind of problem? Any idea how to approach/resolve it or what can be the cause?
    Java is 1.6.20, I have seen the behavior on Windows XP, Vista and 2008. It is not reproducible, it just happens sometimes. I haven't seen that on Java 5. Turning off double buffering resolves that, but is not feasible due to degraded user experience.
    Thanks in advance for your help!
    Jakub

    Thanks for your help so far, perhabs this is something with the driver, but I use fairly generic windows distribution.
    EDT is not hosed, it is processing events normally (I checked that on debug step-by-step). We do not override any paint methods, and this is rather something on different level - it is not "a component not being repainted" it is "everything is repainted, but not shown on screen". Including tabbedPane's tab changes, menu display, etc. I can even see cursor changing into carret when I hover over "not shown" textfield.
    Displaying and then disposing of modal dialog also fixes the state, as do resizing of the JFrame.

  • Properly (?) Double Buffered Applet is really Choppy

    Hi all. I looked around here for the proper way to double buffer an applet, and I think I've got it, but it's realllly choppy when it runs. (It's a little 2d jump 'n run game with not much in it yet). If you have any idea why, please tell =) Thanks!
    public class Game extends JApplet implements KeyListener, Runnable
         //doublebuffer stuff
         Graphics bufferGraphics;
         Image offscreenImage;
         Dimension dim;
         //constants
         int SCREEN_WIDTH = 800;
         int SCREEN_HEIGHT = 600;
         int SPRITE_SIZE = 64;
         Color BGColor = Color.white;
         int PLAYER_SPEED_X = 10;
         int PLAYER_JUMP_SPEED = 20;
         int GRAVITY_ACCEL = 1;
         //directional constants
         int LEFT = -1;
         int RIGHT = 1;
         int STOPPED = 0;
         int UP = -1;
         int DOWN = 1;
         //images
         Image playerImage;
         //movement
         boolean freeFall = true;
         int playerDirX = STOPPED;
         int playerVelY = 0;
         int playerPosX = 0;
         int playerPosY = 0;
         //game control variables
         boolean gameIsRunning = false;
         Thread t;
         int i = 0;
         public void init()
              addKeyListener(this);
              gameIsRunning = true;
              //prepare offscreen image for double buffering
              setSize(800,600);
              dim = getSize();
              offscreenImage = createImage(dim.width,dim.height);
              bufferGraphics = offscreenImage.getGraphics();
              playerImage = getImage(getDocumentBase(),"images/playerRight.gif");
              t = new Thread(this);
              t.start();
         public void run()
              while(gameIsRunning)
                   try
                        t.sleep(33);
                   catch (InterruptedException e) {}
                   playerPosX += playerDirX*PLAYER_SPEED_X;
                   playerPosY -= playerVelY;
                   if(freeFall)
                        playerVelY -= GRAVITY_ACCEL;
                   //wraparound
                   if(playerPosX < 0)
                        playerPosX = 0;
                   if(playerPosX > SCREEN_WIDTH - SPRITE_SIZE)
                        playerPosX = SCREEN_WIDTH - SPRITE_SIZE;
                   //stop at the floor
                   if(playerPosY > SCREEN_HEIGHT - SPRITE_SIZE)
                        freeFall = false;
                        playerVelY = 0;
                        playerPosY = SCREEN_HEIGHT - SPRITE_SIZE;
                   repaint();
         public void keyPressed(KeyEvent e)
              //move right
              if(e.getKeyCode() == KeyEvent.VK_RIGHT ||
                        e.getKeyCode() == KeyEvent.VK_D)
                   playerImage = getImage(getDocumentBase(),"images/playerRight.gif");
                   playerDirX = RIGHT;
              //move left
              if(e.getKeyCode() == KeyEvent.VK_LEFT ||
                        e.getKeyCode() == KeyEvent.VK_A)
                   playerImage = getImage(getDocumentBase(),"images/playerLeft.gif");
                   playerDirX = LEFT;
              //jump
              if(e.getKeyCode() == KeyEvent.VK_SPACE ||
                        e.getKeyCode() == KeyEvent.VK_W ||
                        e.getKeyCode() == KeyEvent.VK_UP)
                   //allow jumping if we're standing on a surface
                   if(playerPosY == SCREEN_HEIGHT - SPRITE_SIZE ||
                             playerPosX == 0 ||
                             playerPosX == SCREEN_WIDTH - SPRITE_SIZE)
                        if(playerPosX == 0)
                             playerDirX = RIGHT;
                             playerImage =
                                  getImage(getDocumentBase(),"images/playerRight.gif");
                        if(playerPosX == SCREEN_WIDTH - SPRITE_SIZE)
                             playerDirX = LEFT;
                             playerImage =
                                  getImage(getDocumentBase(),"images/playerLeft.gif");
                        freeFall = true;
                        playerVelY = PLAYER_JUMP_SPEED;
         public void keyReleased(KeyEvent e)
              //stop moving right
              if(e.getKeyCode() == KeyEvent.VK_RIGHT ||
                        e.getKeyCode() == KeyEvent.VK_D)
                   if(playerDirX == RIGHT)
                        playerDirX = STOPPED;
              //stop moving left
              if(e.getKeyCode() == KeyEvent.VK_LEFT ||
                        e.getKeyCode() == KeyEvent.VK_A)
                   if(playerDirX == LEFT)
                        playerDirX = STOPPED;
         public void keyTyped(KeyEvent e)
         public void paint(Graphics g)
              //clear screen
              bufferGraphics.setColor(Color.white);
              bufferGraphics.fillRect(0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
              //draw the player
              bufferGraphics.drawImage(playerImage,playerPosX,playerPosY,this);
              g.drawImage(offscreenImage,0,0,this);
         public void stop()
              t.stop();
        public void update(Graphics g)
             paint(g);
    }

    It looks fine to me, but don't reload the player images every time. If you need a different image you should read up on AffineTransform and do some rotations etc, or at least have the 4 images in an array or something.
    P.S. stop is deprecated for threads. If you are done with the thread null it. That being said, if you are making this as an applet, make sure you can restart or reload it properly by testing it with the appletvier.
    Good luck in your work.

  • Double Buffering in Java Swing

    Hi sir,
    Here i want to know about what is exactly double buffering?
    I have learned that double buffering is automatic in swing components.
    But i have some problem with my JButtons it is FLICKERING a bit.Where u need to scroll the mouse to see it.Can be provide any idea for this.
    And also give some sample examples related to double buffering.
    Thanx,
    m.ananthu

    Hi sir,
    I have a problem with repainting and validate methods.
    In my project when i click a startbutton it will show a row of 4 buttons and when i click it again that 4 buttons should disappear.All this features are working well.But when i again click the startbutton
    the 4 buttons are not showing in the second time but when i use the
    mouse and scroll over 4 buttons area it is showing the 4 buttons.
    I have used repaint() and validate() methods still there is no use.
    so Pls. do help me.Is it any thing to do with double buffering ?It is
    Urgent.Here is my problem code:-
    Here is the code where MenuOptionList is a class that contains 4 buttons I have used the instance of the MenuoptionList here.Here when i click the "Start" which is for the start button Menuoptionlist will show which contains the row of 4 buttons as u can see there i have used a Flag=false for the first click (ie) to show the row of 4 buttons and in the next i have set the Flag=true to make the 4 buttons disappear all this features are working fine where jp.add(mol) means "jp" is a panel which is set it in the beginning of my home page with setBounds in to it i am adding the mol(instance of MenuoptionList).Here the problem is when i click the StartButton the 4 button are displaying & when i click it next time they are disappearing that all works fine.But when i click it for the next the 4 buttons should show.The problwem is they are showing but they are invisible in such a case if scroll the mouse over the 4 buttons area they are visible.What is the problem here.I have used repaint(),validate() methods still no use.Is the problem is to do with any instance removal.Pls.do help me.It is Urgent
    public void actionPerformed(ActionEvent e)
    changeCenterPanel(e.getActionCommand());
    private void changeCenterPanel(String buttonEvent){
    if((buttonEvent.equals("Start"))&&(Flag==false)){
    mol=new MenuOptionList(jp,jp1,jp2);//Which contains the 4 buttons
    mol.setBounds(150,1,500,600);
    Color c1=new Color(116,121,184);
    mol.setBackground(c1);
    mol.validate();
    mol.repaint();
    jp.add(mol);
    jp.validate();
    jp.repaint();
    Flag=true;
    else if((buttonEvent.equals("Start"))&&(Flag==true))
    mol.removeAll();//removing the 4 buttons
    mol.validate();
    mol.repaint();
    Flag=false;
    Thanx,
    m.ananthu

  • Fine Tuning Java 1.1 Double Buffering?

    Dear Java gurus,
    Hi, I'm looking for suggestions on improving the performance of my double buffering technique for pure Java 1.1 applets.
    My current method seems to eat up more CPU & RAM than it should. I fear that real implementations (with far more drawing to the buffer before update), would be impractically slow and choke using double buffering the way I am now.
    I have programmed a simple applet demonstrating my current method (code below), which runs at 20 fps. I tried to keep it short and sweet.
    I'm only looking for pure Java 1.1 code.
    Thanks in advance. =)
    import java.awt.*;
    import java.applet.*;
    public class ColourFader extends Applet implements Runnable {
    // Class Variables
         int appletWidth = 600;
         int appletHeight = 300;
         int fps = 20;
         int delay = 1000 / fps;
         int nextRGB [] = {255, 0, 255};
         int currRGB [] = {0, 255, 0};
    // Class Objects
         Image offImage;
         Graphics offGraphics;
         Thread animator;
    // Applet Methods          
         public void start() {
              animator = new Thread(this);
              animator.start();
              offImage = createImage(appletWidth, appletHeight);
              offGraphics = offImage.getGraphics();
         public void stop() {
              animator = null;
              offImage = null;
              offGraphics = null;
         public void paint(Graphics g) {
              g.drawImage(offImage, 0, 0, null);
              update(g);
    // Runnable Method
         public void run() {
              while(Thread.currentThread() == animator) {
                   long tm = System.currentTimeMillis();
                   repaint();
                   try {
                        tm += delay;
                        Thread.sleep(Math.max(0, tm - System.currentTimeMillis()));
                   } catch (InterruptedException e) {
                        break;
    // Convenience Methods
         public void update(Graphics g) {
              fadeRGBValues();
              paintFrame(offGraphics);
              g.drawImage(offImage, 0, 0, null);
         public void paintFrame(Graphics g) {
              g.setColor(new Color(currRGB[0], currRGB[1], currRGB[2]));
              g.fillRect(0, 0, appletWidth, appletHeight);          
         public void fadeRGBValues() {
              for(int i = 0; i <= 2; i++) {
                   if(currRGB[i] < nextRGB) {
                        currRGB[i] += 1;
                   } else if (currRGB[i] > nextRGB[i]) {
                        currRGB[i] -= 1;
                   } else {
                        nextRGB[i] = randomNum();
         public int randomNum() {
              double randomDouble = Math.random() * 255.0;
              int randomInt = (int) randomDouble;
              return(randomInt);

    Usually first update is called, then paint. In your paint method you call update, I don't see any reason for that. You want your paint method to be fast, so I would remove the update call.
    Instead I would call paint from the update method. Update is not needed to be called as often as the paint method. I think I would make the update method do nothing (just call the paint method). Then I would make another method I could call when I need to make some updates, and which did not take any graphics object as argument, becuase you dont need it.
    So something like this:
    public void update(Graphics g) {
      paint(g);
    public void paint(Graphics g) {
      g.drawImage(offImage, 0, 0, null);
    public void update() {
      fadeRGBValues();
      paintFrame(offGraphics); 
    }Then in your run method, just before repaint(), I would call update().
    Thread.sleep(0) would sleep forever I think. So be careful with that. A better way to do it:
    public void run() {
      long start = System.currentTimeMillis();
      int count = 0;
      while (Thread.currentThread() == animator) {
        update();
        repaint();
        count++;
        long sleep = count*delay-(System.currentTimeMillis()-start);
        if (sleep > 0) {
          try {
            Thread.sleep(sleep);
          } catch (InterruptedException e) {
            break;
    }

  • Need help with double buffering

    Hi!
    I'm trying to write an animated applet the shows the Java Duke waving.
    No problem getting it to work, but the applet is flickering and I sence the need for double buffering.
    I've tried to use "traditional" double buffering techniques without success. Something like this:
    currentDuke = bufferGraphics.getGraphics();
    public void update(Graphics g) {
        bufferGraphics.clearRect(0, 0, this.getWidth(), this.getHeight());
        paint(g);
    public void paint(Graphics g) {
        bufferGraphics.drawImage(nextDuke, 0, 0, this);
        g.drawImage(currentDuke, 0, 0, this);
    }Didn't help...
    Here's my current code:
    import javax.swing.*;
    import java.awt.*;
    * This is a simple animation applet showing Duke waving.
    * @author Andrew
    * @version 1.0 2002-07-04
    public class WavingDuke extends JApplet implements Runnable {
        private Image[] duke;
        private Image currentDuke;
        private Thread wave;
         * Called by the browser or applet viewer to inform this applet that it has
         * been loaded into the system.
        public void init() {
            loadDuke();
            currentDuke = this.createImage(this.getWidth(), this.getHeight());
         * Called by the browser or applet viewer to inform this applet that it
         * should start its execution.
        public void start() {
            if (wave == null) {
                wave = new Thread(this);
                wave.start();
         * Loads all the duke images into a <code>Image</code> array.
        private void loadDuke() {
            duke = new Image[10];
            for (int i = 0; i < 10; i++) {
                duke[i] = this.getImage(this.getCodeBase(), "images/duke"+i+".gif");
         * Method cycles through different images and calls <code>repaint</code>
         * to make an animation. After each call to <code>repaint</code> the thread
         * sleeps for predefined amount of time.
        public void run() {
            while (true) {
                for (int i = 0; i < 10; i++) {
                    currentDuke = duke;
    repaint();
    paus(150);
    * Method makes the current thread to sleep for tha amount of time
    * specified in parameter <code>ms</code>.
    * @param ms The time to wait specified in milliseconds.
    private void paus(int ms) {
    try {
    Thread.sleep(ms);
    } catch (InterruptedException ie) {
    System.err.println(ie.getMessage());
    * Updates this component.
    * @param g The specified context to use for updating.
    public void update(Graphics g) {
    paint(g);
    * Paints this component.
    * @param g The graphics context to use for painting.
    public void paint(Graphics g) {
    g.clearRect(0, 0, this.getWidth(), this.getHeight());
    g.drawImage(currentDuke, 0, 0, this);
    Thanks in advance!
    /Andrew

    I've solved it!
    /Andrew

  • Dragging a drawing when double-buffering

    Hopefully someone out there can help me with this...
    To state the situation simply, I have an applet in which I need to select, drag, and drop in order to move them around. The applet works fine right now, but I can't figure out how to add dragging. The way I have it, you click the object, drag the mouse to where you want to move it, and let go. It then dissapears from where it was, and appears where it was placed. The prolem is that I want to actively see the object being dragged....even an outline would work. As it is, it's difficult to know what you were selecting to move.
    I added a mouseDragged() function to the program, but I see no evidence of it working, which I think has something to do with the double-buffering I used. As far as I can tell, it does draw the object being dragged, it just doesn't ever show up on the screen....
    I would appreciate any input anyone can offer!

    With double buffering
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.awt.image.BufferedImage;
    public class Omove extends Frame
         BufferedImage img;
         Graphics      mg;
         Vector  v  = new Vector();
         Mobject m;
         int    iv = -1;
         int    dx = -1;
         int    dy = -1;
    public Omove()
         addWindowListener(new WindowAdapter()
        {     public void windowClosing(WindowEvent ev)
              {     dispose();
                   System.exit(0);}});
         setBounds(10,10,400,300);
         v.add(new Mobject(1,30,30));
         v.add(new Mobject(1,89,120));
         v.add(new Mobject(2,130,230));
         v.add(new Mobject(3,210,60));
         addMouseListener(new MouseAdapter()     
         {     public void mouseReleased(MouseEvent m)
                   if (iv != -1) putTheObject(m.getX(),m.getY());               
         addMouseMotionListener(new MouseMotionAdapter()          
              {     public void mouseDragged(MouseEvent m)
                        if (dx == -1) findTheObject(m.getX(),m.getY());     
                        if (iv != -1)
                             dx = m.getX();     
                             dy = m.getY();
                             repaint();
         setVisible(true);
    private void findTheObject(int x, int y)
         for (int i=0; i < v.size(); i++)
              m = (Mobject)v.get(i);
              if (x >= m.x && y >= m.y && x <= m.x+30 && y <= m.y+30)
                   iv = i;
    private void putTheObject(int x,int y)
         iv = -1;
         dx = -1;
    public void paint(Graphics g)
         if (img == null)
              img = (BufferedImage)this.createImage(getWidth(),getHeight());
              mg  = img.getGraphics();
         mg.setColor(Color.white);
         mg.fillRect(0,0,getWidth(),getHeight());
         for (int i=0; i < v.size(); i++)
              m = (Mobject)v.get(i);
              if (iv == i)           
                   m.x = dx;
                   m.y = dy;
              m.draw(mg);
         g.drawImage(img,0,0,null);
    public void update(Graphics g)
         paint(g);
    public class Mobject
         int x,y,t;
    public Mobject(int t, int x, int y)
         this.t = t;     
         this.x = x;     
         this.y = y;     
    public void draw(Graphics g)
         if (t == 1)
              g.setColor(Color.red);
              g.fillRect(x,y,30,30);
         if (t == 2)
              g.setColor(Color.orange);
              g.fillOval(x,y,30,30);
         if (t == 3)
              g.setColor(Color.blue);
              g.fillOval(x,y,50,30);
    public static void main (String[] args)
         new Omove();
    Noah

Maybe you are looking for

  • Cannot install GoLive 8.01 0n new MacBook Pro/Snow leopard

    Purchased a brand new MacBook Pro (with the new Snow leopard) so I could leave my house and still work. The most important application I use is Adobe golive CS2 8.01. I have the 6.0 disk, and the upgrade registration number but they will not install

  • PXE not working after adding second DP

    Hello, i'm having a very strange issue, i had installed a second DP in my environment, all looked to work fine, but now my clients using PXE boot refer to that new server when doing PXE boot, even if my DHCP is setup to refer to my first server (with

  • SAP MM Agewise Stock Standard report in Days

    <b>Dear MM Guys              In sap mm Any standard report available for Agewise stock in days. format. pls tell me.. Regards Anandkumar.</b>

  • Adobe reader and standard "not responding"

    Whenever I try to open a pdf it says "not responding" and teh screen greys out. After about 5 minutes it finally responds.

  • Some apps crash after I use new net modem

    I instal a new modem D-Link (ethernet) with TV service O2. When I connect modem to computer applications like a FCP or Motion launch, but I can see rainbow circle and it is all. After a few seconds comp. freeze and I cannot do anything. I must restar