Double buffering for shape animation

Hello people,
I'm building an applet which animates some text (a shape with various setting for stroke, fill, etc.) and translating it from x1 to x2 using AffineTransform. How can I clear the screen to create an animation effect and double buffering to avoid flickering? Double buffering can be used with ImageS, but what about ShapeS?
Many thanks

Double buffering is a general concept that applies to all
graphic objects.

Similar Messages

  • 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

  • Double Buffering and Components

    Hello I am wondering how do I turn off double buffering for my components. This is important for printing as double buffering makes the print job alot of MB

      /** The speed and quality of printing suffers dramatically if
       *  any of the containers have double buffering turned on.
       *  So this turns if off globally.
       *  @see enableDoubleBuffering
      public static void disableDoubleBuffering(Component c) {
        RepaintManager currentManager = RepaintManager.currentManager(c);
        currentManager.setDoubleBufferingEnabled(false);
      /** Re-enables double buffering globally. */
      public static void enableDoubleBuffering(Component c) {
        RepaintManager currentManager = RepaintManager.currentManager(c);
        currentManager.setDoubleBufferingEnabled(true);
      }

  • Xlet GAMES - HCompenent + double buffering

    Hi all,
    I am writing an application that use some HCompenents (Htext,HTextbuttom...) from package org.havi.ui
    paint method of Hvisible is not implement double buffering (public boolean isDoubleBuffered() { return false;})
    if i want to implement double buffering does the only way to do so is to extends each HCompenent and overwrite the paint function ?
    and how do i implement double buffering for part of the screen?
    i need to use bufferImage and bufferGraphics or there is some flip method
    Thanks

    You can either extend each HComponent or you can use HLooks to do implement double buffering. Writing a good HLook is tricky, but it may be slightly easier that extending each HComponent, depending on how many classes you have.
    Steve.

  • Sprite animation with double buffering

    Hello, I am writing a game. I am not using swing. Just awt.
    I have several books I am looking at right now. One uses the
    BufferedImage class to create a buffered sprite. The other book instead uses the Image class to impliment double buffering. So, I am really confused now. I do not know if I should use the BufferedImage class or the Image class. Note that
    Please help. Which method is the best to use?
    Val

    These links may assist you in full-screen animation with double-buffering:
    http://www.sys-con.com/java/article.cfm?id=1893
    http://www.meatfighter.com/meat.pdf
    - Mike

  • Code for Double Buffering

    Hi.
    I did go through the JAVA tutorial here, but I still am not very clear about how to do double buffering. Can someone just give me a sample code? It would make my understanding clearer.
    Also, for making games like mario or contra, should I use .gif images or .jpg?
    Thanking You all

    private Image offScreenImage;
    private Graphics offScreen;
    public void update(Graphics g){
    offScreenImage=createImage(this.getSize().width, this.getSize().height);
    offScreen=offScreenImage.getGraphics();
    paint(offScreen);
    g.drawImage(offScreenImage,0,0,this);
    there you go... enjoy =)
    Michael

  • Double buffering circle not round anymore

    I am making an applet where some circles are painted to the screen. When not using the double buffering scenario, the shapes appear correctly.
    The problem is when i use the double-buffering technique, the circles are still there, but they look like very ugly. I would call that some "squarcles".
    What is the bug here and how to get some decent double buffering with thoses circles?

    Ok, i had some problem with the running thread when closing the applet viewer, but now this situation is corrected by setting the animation thread to null before calling stop().
    Maybe explanation of the problem is not clear, so i made two versions of the same applet with only 2 lines of code different so that there is one applet that is not double buffered.
    You can check these by yourself at this place:
    Double buffered circles: http://www.geocities.com/xeneve/cooltrail/ demo_cooltrail.htm
    No double buffer:
    http://www.geocities.com/xeneve/cooltrail/demo_cooltrail_ndb.htm
    This is just annoying to get this result. I realise that maybe not many peoples are coding applets so i guess there is few people that may have a workaround for this.

  • 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

  • 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 circle not round

    I am making an applet where some circles are painted to the screen. When not using the double buffering scenario, the shapes appear correctly.
    The problem is when i use the double-buffering technique, the circles are still there, but they look like very ugly. I would call that some "squarcles".
    What is the bug here and how to get some decent double buffering with thoses circles?

    Here is the code so far i have that is used for painting on the screen:
    // Declaration
    private BufferedImage ecran;
    private Graphics2D buffer_ecran;
    // Instantiation
    this.ecran = new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_ARGB);
    this.buffer_ecran = ecran.createGraphics();
    // In paint() method
    Graphics be = buffer_ecran;
      // Clean the surface
    be.setColor(Color.WHITE);
    be.fillRect(0, 0, getSize().width, getSize().height);
      // Draw the circles
    be.setColor(Color.RED);
    be.drawOval(x, y, ra, rb);
      // Output the buffer to the screen
    g.drawImage(ecran, 0, 0, this);I was previously using Image and changed to BufferedImage with the hope it would resolve the situation. I can't tell a significant change in image display.

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

  • 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

Maybe you are looking for

  • Empty BPF in Content Library

    Dear BPC fans, After I'm happy with my BPF design in BPC Admin and tested it in BPC Web, it works, I started to put it in Content Library. So inside the Content Library, I created a web page with BPF in it. Strange, the BPF's steps doesn't show up. I

  • ClickOnce, Windows 8+, SmartScreen, Unknown Publisher & EV Certificate

    In an attempt to eliminate the Smart Screen warning in Windows 8+, my company purchased an EV Certificate from Symantec to use for a software product we produce. Specifically it is called: Symantec Class 3 Extended Validation Code Signing CA – G2. We

  • 2G Ipod Touch - iOS 3.1.3 - ITunes 10.1 - Can't upgrade to version iOS4.2.

    I hope someone can offer any information about how I can get my Ipod upgraded. When I run Itunes, I get the message that 3.1.3 is already the current version. I have tried reinstalling ITunes, completely resetting my Ipod. I am certain that my device

  • Safari 5.0.1 Keeps crashing. Please help

    Process: Safari [2548] Path: /Applications/Safari.app/Contents/MacOS/Safari Identifier: com.apple.Safari Version: 5.0.1 (6533.17.8) Build Info: WebBrowser-75331708~1 Code Type: X86 (Native) Parent Process: launchd [98] Date/Time: 2010-07-28 12:58:43.

  • Connect Select 360 to Intel iMac...

    Hi - How can I connect a LaserWriter Select 360 to an Intel iMac? I have an existing ethernet network, but the 360 has no eithernet connection on it. Is it possible to go from a serial port connection or a scuzzy (sp?) port to an ethernet network (i.