Double buffering images

HELP!!! lol i'm trying to figure out how to get the whole double buffering thing to work with a picture like a gif image i drew in paint. i can't quite understand anything aobut how to do it. lol i've read some things and looked at some code samples but they all do it with a polygon. i just can't seem to get it right. i learn best from code snipets if that helps. don't give me a whole program i just want some lines that will help me learn it like what i have to import. and other things. i know a little about using images but not a whole lot. if anyone can help it will be appreciated.
andy

Psst... Tell you teacher that one can read an image with ImageIO, often in one line:
BufferedImage image = ImageIO.read(file_or_url_or_inputstream);(No need for a MediaTracker!) And the resulting BufferedImage (a subclass of Image)
is easier to work with than Image and has more useful features.
Welcome to Java 2D.

Similar Messages

  • Double Buffering a large image - is it a good idea to do so ?

    I'm developing a small maze like game. I'm using double buffering. So I double buffer the enter screen area (1024x768) and copy them all back to the on screen buffer...
    I need my code to run atleast at 18 - 24 fps.
    Is there a better/efficient way to do this...
    Note : I'm manually double buffer. I don't use any Buffer manager.
    like this
    public void update(Graphics g)
          Image i = createImage(...)      ;
          paint(i.getGraphics() );
          g.drawImage(i..)
    }

    Hi chaos,
    I am developing a game too and I achieve very high frame rate (up to 60 fps) using the hardware accelerated pipelines and the double buffering/page flipping strategy.
    here is the method I call to update my the entire screen of my game:
    private void screenUpdate()
        try
          Graphics gScr = bufferStrategy.getDrawGraphics();
          gameRender(gScr); //this is where I paint the game screen
          gScr.dispose();
          if (!bufferStrategy.contentsLost())
            bufferStrategy.show();
        } catch (Exception e)
          e.printStackTrace();
          running = false;
      }Here is how I create the buffer strategy in the main JFrame:
    try
          EventQueue.invokeAndWait(new Runnable()
            public void run()
              createBufferStrategy(NUM_BUFFERS);
        } catch (Exception e)
          System.out.println("Error while creating buffer strategy");
          System.exit(0);
        bufferStrategy = getBufferStrategy();In my gameRender method, I use only draming method that works without breaking the hardware acceleration (by default enabled with java 6.0). I just make sure to use BufferedImage without rotation or manually written filters and the game runs at 60 fps without any issue.
    The CPU is even still sleeping more than 70% of the time which gives a lot room for all other processing such as path finders, A.I., ...
    Cheers.
    Vince.

  • 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

  • How do I fix extremely slow rendering with buffered images?

    I've found random examples of people with this problem, but I can't seem to find any solutions in my googling. So I figured I'd go to the source. Basically, I am working on a simple platform game in java (an applet) as a surprise present for my girlfriend. The mechanics work fine, and are actually really fast, but the graphics are AWFUL. I wanted to capture some oldschool flavor, so I want to render several backgrounds scrolling in paralax (the closest background scrolls faster than far backgrounds). All I did was take a buffered image and create a graphics context for it. I pass that graphics context through several functions, drawing the background, the distant paralax, the player/entities, particles, and finally close paralax.
    Only problem is it runs at like 5 fps (estimated, I havn't actually counted).
    I KNOW this is a graphics thing, because I can make it run quite smoothly by commenting out the code to draw the background/paralax backgrounds... and that code is nothing more complicated than a graphics2d.drawImage
    So obviously I am doing something wrong here... how do I speed this up?
    Code for main class follows:
    import javax.swing.JApplet;
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.awt.event.*;
    import Entities.*;
    import Worlds.*;
    // run this applet in 640x480
    public class Orkz extends JApplet implements Runnable, KeyListener
         double x_pos = 10;
         double y_pos = 400;
         int xRes=640;
         int yRes=480;
         boolean up_held;
         boolean down_held;
         boolean left_held;
         boolean right_held;
         boolean jump_held;
         Player player;
         World world;
         BufferedImage buffer;
         Graphics2D bufferG2D;
         int radius = 20;
         public void init()
              //xRes=(int) this.getSize().getWidth();
              //yRes=(int) this.getSize().getHeight();
            buffer=new BufferedImage(xRes, yRes, BufferedImage.TYPE_INT_RGB);
            bufferG2D=buffer.createGraphics();
              addKeyListener(this);
         public void start ()
                player=new Player(320, 240, xRes,yRes);
                world=new WorldOne(player, getCodeBase(), xRes, yRes);
                player.setWorld(world);
               // define a new thread
               Thread th = new Thread (this);
               // start this thread
               th.start ();
         public void keyPressed(KeyEvent e)
              //works fine
         }//end public void keypressed
         public void keyReleased(KeyEvent e)
              //this works fine
         public void keyTyped(KeyEvent e)
         public void paint( Graphics g )
               update( g );
        public void update(Graphics g)
             Graphics2D g2 = (Graphics2D)g;              
             world.render(bufferG2D);                
             g2.drawImage(buffer, null, null);
         public void run()
              // lower ThreadPriority
              Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
              long tm;
              long tm2;
              long tm3;
              long tmAhead=0;
              // run a long while (true) this means in our case "always"
              while (true)
                   tm = System.currentTimeMillis();
                   player.moveEntity();
                  x_pos=player.getXPos();
                  y_pos=player.getYPos();
                  tm2 = System.currentTimeMillis();
                    if ((tm2-tm)<20)
                     // repaint the applet
                     repaint();
                    else
                         System.out.println("Skipped draw");
                    tm3= System.currentTimeMillis();
                    tmAhead=25-(tm3-tm);
                    try
                        if (tmAhead>0) 
                         // Stop thread for 20 milliseconds
                          Thread.sleep (tmAhead);
                          tmAhead=0;
                        else
                             System.out.println("Behind");
                    catch (InterruptedException ex)
                          System.out.println("Exception");
                    // set ThreadPriority to maximum value
                    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
         public void stop() { }
         public void destroy() { }
    }Here's the code for the first level
    package Worlds;
    import java.awt.Color;
    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    import java.util.*;
    import javax.swing.*;
    import javax.imageio.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.io.File;
    import java.net.URL;
    import java.awt.geom.AffineTransform;
    import Entities.Player;
    public class WorldOne implements World
         Player player;
         //Location of Applet
         URL codeBase;
         // Image Resources
         BufferedImage paralax1Image;
         BufferedImage paralax2Image;
         BufferedImage backgroundImage;
         // Graphics Elements     
         int xRes;
         int yRes;
         double paralaxScale1,paralaxScale2;
         double worldSize;
         int frameX=1;
         int frameY=1;
         public WorldOne(Player player, URL codeBase, int xRes, int yRes)
              this.player=player;
              this.codeBase=codeBase;
              this.xRes=xRes;
              this.yRes=yRes;
              worldSize=4000;
            String backgroundImagePath="worlds\\world1Graphics\\WorldOneBack.png";
            String paralax1ImagePath="worlds\\world1Graphics\\WorldOnePara1.png";
            String paralax2ImagePath="worlds\\world1Graphics\\WorldOnePara2.png";
            try
            URL url1 = new URL(codeBase, backgroundImagePath);
             URL url2 = new URL(codeBase, paralax1ImagePath);
             URL url3 = new URL(codeBase, paralax2ImagePath);
            backgroundImage = ImageIO.read(url1);
            paralax1Image  = ImageIO.read(url2);
            paralax2Image = ImageIO.read(url3);
            paralaxScale1=(paralax1Image.getWidth()-xRes)/worldSize;
            paralaxScale2=(paralax2Image.getWidth()-xRes)/worldSize;
            catch (Exception e)
                 System.out.println("Failed to load Background Images in Scene");
                 System.out.println("Background Image Path:"+backgroundImagePath);
                 System.out.println("Background Image Path:"+paralax1ImagePath);
                 System.out.println("Background Image Path:"+paralax2ImagePath);
         }//end constructor
         public double getWorldSize()
              double xPos=player.getXPos();
              return worldSize;
         public void setFramePos(int frameX, int frameY)
              this.frameX=frameX;
              this.frameY=frameY;
         public int getFrameXPos()
              return frameX;
         public int getFrameYPos()
              return frameY;
         public void paralax1Render(Graphics2D renderSpace)
              int scaledFrame=(int)(paralaxScale1*frameX);
              renderSpace.drawImage(paralax1Image,-scaledFrame,0,null); //Comment this to increase performance Massively
         public void paralax2Render(Graphics2D renderSpace)
              int scaledFrame=(int)(paralaxScale2*frameX);
              renderSpace.drawImage(paralax2Image,-scaledFrame,0,null); //Comment this to increase performance Massively
         public void backgroundRender(Graphics2D renderSpace)
              renderSpace.drawImage(backgroundImage,null,null); //Comment this to increase performance Massively
         public void entityRender(Graphics2D renderSpace)
              //System.out.println(frameX);
              double xPos=player.getXPos()-frameX+xRes/2;
             double yPos=player.getYPos();
             int radius=15;
             renderSpace.setColor (Color.blue);
            // paint a filled colored circle
             renderSpace.fillOval ((int)xPos - radius, (int)yPos - radius, 2 * radius, 2 * radius);
              renderSpace.setColor(Color.blue);
         public void particleRender(Graphics2D renderSpace)
              //NYI
         public void render(Graphics2D renderSpace)
              backgroundRender(renderSpace);
              paralax2Render(renderSpace);
              entityRender(renderSpace);
              paralax1Render(renderSpace);
    }//end class WorldOneI can post more of the code if people need clarification. And to emphasize, if I take off the calls to display the background images (the 3 lines where you do this are noted), it works just fine, so this is purely a graphical slowdown, not anything else.
    Edited by: CthulhuChild on Oct 27, 2008 10:04 PM

    are the parallax images translucent by any chance? The most efficient way to draw images with transparent areas is to do something like this:
         public static BufferedImage optimizeImage(BufferedImage img)
              GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();                    
              GraphicsConfiguration gc = gd.getDefaultConfiguration();
              boolean istransparent = img.getColorModel().hasAlpha();
              BufferedImage img2 = gc.createCompatibleImage(img.getWidth(), img.getHeight(), istransparent ? Transparency.BITMASK : Transparency.OPAQUE);
              Graphics2D g = img2.createGraphics();
              g.drawImage(img, 0, 0, null);
              g.dispose();
              return img2;
         }I copied this from a util class I have and I had to modify it a little, I hope I didn't break anything.
    This piece of code does a number of things:
    - it allows the images to be hardware accelerated
    - the returned image is 100% compatible with the display, regardless of what the input image is
    - BITMASK transparent images are an incredible amount faster than translucent images
    BITMASK means that a pixel is either fully transparent or it is fully opaque; there is no alpha blending being performed. Alpha blending in software rendering mode is very slow, so this may be the bottleneck that is bothering you.
    If you require your parallax images to be translucent then I wouldn't know how to get it to draw quicker in an applet, other than trying out java 6 update 10 to see if it fixes things.

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

    Hi there......
    Ive created a game that uses double buffering...basically the user hits the ball that is moving around the screen... after 5 goes the program needs to display a graph....
    I have got the two components working seperatly... but when i combine that classes into one (the graph + the game) when theg graph is displayed the screen flickers..... and u cant see the graph properly....
    How do you stop the screen from trying to keep refreshing and display the final image? (which is no longer animated)
    Many thanks....

    search this site or google
    there are hundreds of posts about double buffering

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

  • Double buffering on large pane

    I have a large JPanel which I'm drawing onto which is about 5000 x 5000. To eliminate screen flicker when dragging objects I'm trying to use double buffering. The problem is the image is too big and I get an out of memory error message.
    I've tried using clipped rectangles to display just the size of image needed but they give erratic results or the scrolling doesn't work. I need it to display the rest of the image when scrolling. Does anyone have any suggestions on how to solve this?
    I've thought about creating the image to be just the size of the screen and to just have the objects that are meant to be at that part but I think this would involve going from device space from user space but I don't know how to do this. Thanks.
    Alan

    ok, if you want it to be interactive with scrolling, then you have to keep the image large, but unless your video card has 71.5MB free space for that image, you're not going to get good results, not to mention CPU will be hurting if you need to do any processing of the image (transforms, loads, saves, etc.)
    options:
    1. forget interaction and just get the viewable image area and paint that portion of the image
    2. Get a graphics supercomputer!
    3. try to fake the interaction somehow
    what else? dunno, did that help

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

  • Drawing with double buffering to a JFrame

    I want to create a simple JFrame and draw stuff to it via Graphic object using double buffering.
    If I create a loop and draw constantly using JFrame.getGraphic().xxx, am i doing double buffering. ( 'cause i read somewhere that swing components automaticly use double buffering ). And is this the righ approuch ( or whatever it's spelled ) ?

    I want to create a simple JFrame and draw stuff to it
    Don't do that.
    If you want to do custom rendering then use JPanel or JComponent, not JFrame.
    If I create a loop and draw constantly using JFrame.getGraphic().xxx, am i doing double buffering.
    No.
    You're also painting outside the standard paint cycle, which is a Bad Idea.
    So, essentially, everything your suggesting is the wrong way to go about things.
    In its most simple form, double buffering works something like this, though there are a whole load of subtleties to consider (such as component resizing for a start)
    public class Foo extends JComponent
        private BufferedImage image = null;
        protected void paintComponent(Graphics g)
            if (image != null)
                image = createImage(getWidth(), getHeight());
                paintBuffer(ig);
            g.drawImage(image, 0, 0, this);
        private void paintBuffer()
            Graphics ig = image.getGraphics();
            // do the rendering
            ig.dispose();
    }

  • Adding Text to a Buffered Image

    Hey
    I am trying to add text to a bufferedimage image and have tried a couple of ways.
    I cannot seem to get it to work propely though. Everytime i try, the text appears but the image appears inside the lettering of the text and not under it like i want it to.
    Could someone please explain the best way of place text on TOP of an image as i am really stuck now :(
    Thanks in advanced for any help

    Basically paint your buffered image into a new BufferedImage and then paint in the new text on top.
    Here's a demo.
    import java.awt.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    public class BufferedImageTest
        public static void main(String[] args)
            ImageGenerator ig = new ImageGenerator();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(ig.getOriginalImagePanel(), "North");
            f.getContentPane().add(ig.getTextPanel(), "South");
            f.setSize(400,640);
            f.setLocation(200,50);
            f.setVisible(true);
            f.getContentPane().add(ig.getNewImagePanel());
            f.validate();
            f.repaint();
    class ImageGenerator
        JPanel originalPanel = new JPanel()
            public void paintComponent(Graphics g)
                super.paintComponent(g);
                Graphics2D g2 = (Graphics2D)g;
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                    RenderingHints.VALUE_ANTIALIAS_ON);
                int w = getWidth();
                int h = getHeight();
                g2.setPaint(Color.blue);
                g2.fill(new Rectangle2D.Double(w/16, h/16, w*7/8, h*7/8));
                g2.setPaint(Color.yellow);
                g2.fill(new Rectangle2D.Double(w/8, h/8, w*3/4, h*3/4));
                g2.setPaint(Color.red);
                g2.fill(new Ellipse2D.Double(w/6, h/6, w*2/3, h*2/3));
                g2.setPaint(Color.green);
                g2.draw(new Line2D.Double(w/16, h/16, w*15/16, h*15/16));
        JPanel textPanel = new JPanel()
            Font font = new Font("lucida sans regular", Font.PLAIN, 32);
            String text = "A New Label";
            public void paintComponent(Graphics g)
                super.paintComponent(g);
                Graphics2D g2 = (Graphics2D)g;
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                    RenderingHints.VALUE_ANTIALIAS_ON);
                g2.setFont(font);
                FontRenderContext frc = g2.getFontRenderContext();
                LineMetrics lm = font.getLineMetrics(text, frc);
                float textWidth = (float)font.getStringBounds(text, frc).getWidth();
                int w = getWidth();
                int h = getHeight();
                float x = (w - textWidth)/2;
                float y = (h + lm.getHeight())/2 - lm.getDescent();
                g2.drawString(text, x, y);
        public ImageGenerator()
            originalPanel.setBackground(Color.white);
            originalPanel.setPreferredSize(new Dimension(300,200));
            textPanel.setOpaque(false);
            textPanel.setPreferredSize(new Dimension(300,200));
        private BufferedImage createNewImage()
            BufferedImage image = new BufferedImage(originalPanel.getWidth(),
                                                    originalPanel.getHeight(),
                                                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = image.createGraphics();
            originalPanel.paint(g2);
            textPanel.paint(g2);
            g2.dispose();
            return image;
        public JPanel getOriginalImagePanel()
            return originalPanel;
        public JPanel getTextPanel()
            return textPanel;
        public JPanel getNewImagePanel()
            JPanel panel = new JPanel()
                BufferedImage image = createNewImage();
                public void paintComponent(Graphics g)
                    super.paintComponent(g);
                    Graphics2D g2 = (Graphics2D)g;
                    g2.drawImage(image, null, 0, 0);
            return panel;
    }

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

Maybe you are looking for

  • WM error  while creation of production order.

    Hi , I am trying to create a production order . I am getting below error in log as"Movement type for production supply missing in whse 112, storage type SHP" . Can anybody tell me which movement type i am missing here ? Regards Rohit Chavan

  • How to send chr$(195) in Labview (MAX)

    I have an elderly Philips DMM that needs re-calibrating, using the GPIB commands.  I need to send it a character string starting with CHR$(195).  I have a GPIB-USB-HS interface and run Labview 9.  To get me going I have been using the Measurement and

  • Payment Batch

    Dears, Please note that we are grouping our invoices in batch number and this batch number is costumized and when we run concurrent request this number batch will be generated automatically in DFF so we are trying to pay these invoices under the batc

  • Develop a Integrated Report of Program and Project Risks, Issues and Opportunities from Project Sites

    Does anyone know if it is possible to create an integrated report of all program / project risks, issues and opportunities as identified on project sites? We plan on having our project teams identify and manage these on their project sites but would

  • Why do some of my Stations on iTunes Radio stop playing music?

    I'm using iTunes Radio on my iPhone. After listening to it for while it will stop playing music. I'm pretty sure it has something to do with the servers at Apple. Can anyone give me advice on this issue?