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

Similar Messages

  • Double buffering

    I was searching through posts to find an answer to my problem of getting double buffering working without flickering when I came across this response:
    Upgrade your SDK, early 1.4 implementations had this problem on Windows2k (It's a bug). Pretty much the second buffer will point to an empty portion of video memory always, the solution to this without updating is to fill the entire backbuffer completely, flip it, fill it again, and then flip it again. You should then be able to use it normaly.
    -Jason Thomas.
    Since I am on dialup I can't really download the SDK, so could someone give me some code to do what Jason has suggested?
    Jonathan O'Brien

    No I am not recreating the bufferstrategy every frame. Overriding update didn't work either. Here is my code for main:
              GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
              GraphicsDevice device = env.getDefaultScreenDevice();
              GraphicsConfiguration gc = device.getDefaultConfiguration();
              Frame myFrame = new Frame(gc);
    BufferCapabilities bufferCaps = gc.getBufferCapabilities();
              boolean multiBuffer = bufferCaps.isMultiBufferAvailable();
              boolean fullScreen = device.isFullScreenSupported();
              System.out.println("Full screen supported = " + fullScreen);
              System.out.println("Multi buffer available = " + multiBuffer);
              System.out.println("Page flipping = " + bufferCaps.isPageFlipping());
              myFrame.setUndecorated(true);
              myFrame.setIgnoreRepaint(true);
              if ((fullScreen) && (multiBuffer))
                   device.setFullScreenWindow(myFrame);
                   device.setDisplayMode(new DisplayMode(800, 600, 16, 0));
                   rectBounds = myFrame.getBounds();
                   myFrame.createBufferStrategy(2);
                   bufferStrategy = myFrame.getBufferStrategy();
                   bufferReady = true;
              Game thisGame = new Game(args[0]);
              myFrame.add(thisGame);
    //          myFrame.getContentPane().add(thisGame);
              myFrame.show();
    And here is the relevant code for my run method:
              if (bufferReady)
                   Graphics g = bufferStrategy.getDrawGraphics();
                   if (!bufferStrategy.contentsLost()) {
                        g.fillRect(0,0,getWidth(),getHeight());
                        g.dispose();
                        bufferStrategy.show();

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

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

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

  • 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

  • JNI native drawing - Double Buffering issue

    Hi,
    I use JNI to paint from a C++ DLL onto a canvas, which works fine.
    The problem is that double buffering is not working though.
    In C++ I create an offscreen HDC, draw something on it and finally i bitblit the offscreen HDC to the parent window HDC.
    That is how double buffering is supposed to work. But each time i repaint my Canvas in Java, i see flickering:
    the background color is displayed first, then the C++ paintings are drawn.
    Since i already do double buffering in my C++ drawings, i don't know why there still is flickering.
    Should i do double buffering on my canvas also?
    How would this work, since my paint method looks like;
         private native void drawChart(Graphics g);
         public void paint(Graphics g)
              drawChart(g);
         }

    this is my lucky day :)
    the following thread on http://forum.java.sun.com/thread.jspa?threadID=562392&messageID=2767046 suggested to override the update method on the canvas, which works.
         // overridden to eliminate flicker
        public void update(Graphics g)
            paint(g);
        }

  • 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

  • Flickering graphics

    Hi, I programmed my java applet and on my computer it works fine. The image doesn't flicker, but when i run it on someone else's computer and the image totally flickers.
    I am using a JPanel. I render my graphics in a separate function then in the paintComponent function i call the super and then paint my rendered graphics to the JPanel. I tried setting double buffering to true for my JPanel but it didn't help. If i set my program to render the screen less often the flickering is reduced but still there.
    Also it seems like the things that get painted last in my render function are visible less often whereas the things that are painted first in my render function flicker very little.

    Okay here is as close as i can get to an SSCCE. I tried to strip it down to as little as possible and i just threw some random stuff in the gameRender() function to keep it small. It seems to have the flickering problem but i dunno if it will flicker for everyone since my original applet didn't flicker on my own computer.
    package main;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    public class exampleApplet extends JApplet implements ActionListener{
            public Container c;
            private examplePanel game;        // the game panel
            public void init()
                 makeGUI();
                 game.startGame();
           private void makeGUI()
                Container mainCont = getContentPane();
                 mainCont.setLayout( new BorderLayout() ) ;
                     mainCont.setLayout(new GridBagLayout());
                  GridBagConstraints mgbc = new GridBagConstraints();
                  mgbc.fill = GridBagConstraints.BOTH;
                   c = new Container();
                  c.setLayout( new BorderLayout() ); 
                  game = new examplePanel(this);   
                  c.add(game, "Center");
                  mainCont.add(c,mgbc);
         public void actionPerformed(ActionEvent arg0) {
              // TODO Auto-generated method stub
    package main;
         import java.awt.Color;
         import java.awt.Dimension;
         import java.awt.Graphics;
         import java.awt.Image;
         import java.awt.Toolkit;
         import java.awt.event.ActionEvent;
         import java.awt.event.ActionListener;
         import java.util.Random;
         import javax.swing.*;
         public class examplePanel extends JPanel implements Runnable, ActionListener{
              exampleApplet top;
              static final int TOTALWIDTH = 1200;
              static final int TOTALHEIGHT = 700;
              private Thread animator;
              private Random random = new Random(System.nanoTime());
              long lastFrame;
              long period = 15;
              boolean running = false;
              private Image dbImage = null;
              private Graphics dbg;
              public examplePanel(exampleApplet top) {
                   this.top = top;
                   setBackground(Color.blue);
                 setMinimumSize(new Dimension(1200,700));
                 setLayout(null);
                  running = true;
              public void startGame(){
                  if (animator == null || !running) {
                       animator = new Thread(this);
                     animator.start();
              public void run() {
                   while(running){
                        setPreferredSize( new Dimension(TOTALWIDTH, TOTALHEIGHT));
                        lastFrame = System.currentTimeMillis();
                        updateGame(50);
                        gameRender();
                        repaint();
                        long temp = System.currentTimeMillis();
                        if(temp < lastFrame + 15 )
                             period = 15 - temp + lastFrame;
                        try {
                             Thread.sleep(period);
                        } catch (InterruptedException e) {
                             e.printStackTrace();
              private void updateGame(int GAMESPEED){
                   //DO stuff in here
              private void gameRender(){
                  if (dbImage == null){
                    dbImage = createImage(TOTALWIDTH, TOTALHEIGHT);
                    if (dbImage == null) {
                      System.out.println("dbImage is null");
                      return;
                    } else
                      dbg = dbImage.getGraphics();
                  for(int i = 0; i < 100; i++)
                       for(int j = 0; j < 100; j++){
                       dbg.setColor(Color.RED);
                        dbg.fillRect(i*10,j*10, 10, 10);
                  for(int i = 0; i < 50; i++)
                       for(int j = 0; j < 50; j++){
                       dbg.setColor(new Color(0,200,200,100));
                        dbg.fillRect(i*20,j*20, 10, 10);
                  for(int i = 0; i < 50; i++)
                       for(int j = 0; j < 50; j++){
                       dbg.setColor(new Color(50,50,50,50));
                        dbg.fillRect(i*20 + 5,j*20 + 5, 10, 10);
                  for(int i = 25; i < 50; i++)
                       for(int j = 25; j < 50; j++){
                       dbg.setColor(new Color(50,250,50,50));
                        dbg.fillRect(i*20 + 5,j*20 + 5, 20, 20);
              public void paintComponent(Graphics g) {
                   long startTime = System.currentTimeMillis();
                  try {
                   // super.paintComponent(g);
                    if ((g != null) && (dbImage != null))
                         g.drawImage(dbImage, 0, 0, null);
                    Toolkit.getDefaultToolkit().sync();  // sync the display on some systems
                  catch (Exception e)
                  { System.out.println("Graphics error: " + e); }
              public void actionPerformed(ActionEvent e) {          
         }

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

  • 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

  • Flickering, graphical quality

    I am writing a Java program that has to do with moving a shae across the screen. The code is below.
    There a Circle class which Extends the Shape class. The movingBallTest creates the circle and moves it across the screen repeatedly, shifting it down each time. (it leaves a trail as well)
    The problem is that there is considerable flickering. I was hoping to increase the quality as well, maybe by using java2d or something. The code is very basic. Is there any other approach I can take to achieve the same goal? I have added the code below...Please tell me if and where I couldmake changes to improve it.
    Please HELP!!!
    D
    import java.awt.*;
    import java.awt.event.*;
    class MovingBallTest {
    private static Graphics g;
    private static Circle c, c1;
    private static DrawFrame df;
    private static int wsize = 700, hsize = 705;
    private static int x = 0, y = 0, x1 = x, y1 = y, delay = 2, delayNanos = 999, circleDia = 20, xSpace = 6, ySpace = 6, phase = 1;
    private static int baseX = x, baseY = y;
    public static void createWindow(){ //creates the window frame
    df = new DrawFrame("Moving Ball");
    df.show();
    df.setSize(wsize, hsize);
    g = df.getGraphicsContext();
    public static void createShape(){ //creates instances of the ball(s)
    c = new Circle(x, y, Color.blue, circleDia);
    c1 = new Circle(x1, y1, Color.yellow, circleDia);
    public static void resetX(){ //resets the x coordinate of the ball to the left corner of screen
    c.setX(baseX);
    c1.setX(baseX);
    x = baseX;
    public static void moveDownY(int downY){ //moves the y coordinate of the ball down by a given number
    c.move(0, downY);
    c1.move(0, downY);
    public static void changeSpeed(int speed, int nanos){ //changes the time between each refresh
    //You can make...maybe 5 speed settings
    //Level l would have less delay etc.
    delay = speed;
    delayNanos = nanos;
    public static void clearScreen(){ //clears the screen
    g.setColor(Color.white);
    g.fillRect(0, 0, wsize-1, hsize-1);
    public static void moveLine(){ //moves the ball in a straight line across the screen (left to right)
    while(x < wsize - circleDia){
    //g.setColor(Color.white);
    //g.fillRect(0, 0, size-1, size-1);
    //clearScreen();
    x = x + xSpace;
    c.move(xSpace, 0);
    c1.draw(g);
    c.draw(g);
    df.repaint();
    c1.move(xSpace, 0);
    try{
    Thread.sleep(delay, delayNanos);
    catch(InterruptedException e){}
    catch(IllegalArgumentException e){}
    public static void changeYspace(int newySpace){ //changes the spaces jumped as the ball goes down
    ySpace = newySpace;
    public static void main(String[] args){               
    createWindow();
    createShape();
    for(int i = 0; i < 23; i++){
    moveLine();
    resetX();
    clearScreen();
    moveDownY(50);
    import java.awt.*;
    public abstract class Shape{
    private int x;
    private int y;
    private Color color;
    public Shape(int x, int y, Color color){
    this.x = x;
    this.y = y;
    this.color = color;
    public abstract void draw(Graphics g);
    public abstract int getHeight();
    public abstract int getWidth();
    public Color getColor(){
    return color;
    public int getX(){
    return x;
    public int getY(){
    return y;
    public void setX(int x){
    this.x = x;
    public void setY(int y){
    this.y = y;
    public void move(int dx, int dy){
    x += dx;
    y += dy;
    public void setColor(){
    this.color = color;
    import java.awt.*;
    public class Circle extends Shape{
    private int diameter;
    //for a rectangle(for instance) you would need 2 variables
    //one for width and the other for the height etc
    public Circle(int x, int y, Color color, int diameter){
    super(x, y, color);
    this.diameter = diameter;
    public void draw(Graphics g){
    g.setColor(getColor());
    g.fillOval(getX(), getY(), diameter, diameter);
    public int getHeight(){
    return diameter;
    public int getWidth(){
    return diameter;
    }

    You must use double buffering for drawing.
    The old java.awt does not do this automatically, javax.swing does have easier support.
    Look at the demos with the J2SDK, they are very impressive.

  • How to draw a point without double buffering?

    Hello all,
    I am drawing points as small red circles, but they are a bit ugly without double buffering. Am I able to draw the points to be nice? I mean not to draw them as just circles, but some special circle with light border that will looks much more nicer?
    Or what radius and position of the circle must be to be a nice small circle containing only 5 pixels? (upper, lower, right, left, middle)
    ps - they are ugly in the way of having a strange dot on the left side

    I use this method:
        private static final float POINT_RADIUS = 2f;
        private static final float POINT_DIAMETER = POINT_RADIUS * 2;
    private void drawPoint(float x, float y, Color c) {
            Ellipse2D point = new Ellipse2D.Float(x - POINT_RADIUS, -y
                    - POINT_RADIUS, POINT_DIAMETER, POINT_DIAMETER);
            graphics.setStroke(new BasicStroke(0.2f));
            graphics.fill(point);
    // and points looks like this:
       ***

Maybe you are looking for

  • Jdeveloper 10.1.3.2 and sqlplus password prompting

    OK, I downloaded jdeveloper 10.1.3.2. Created a new database connection, let's call it 'TestDBConnection'. In the authentication tab, made sure 'deploy password' was checked. Tested database connection everything works. So far so good. Now create a p

  • HT1459 My ipod touch is disabled.  I forgot the passcode.  How do I get it?

    My ipod touch is disabled.  I forgot the passcode.  How do I get it?

  • Problem applying XSL template for Hash calculation.

    Hi, This may not be exactly a Java problem, I got a problem removing whitespaces in XML via XSL. My XSL: <?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:ns1="http://www.

  • Problem in Create Appointment and instant messaging.

    Hi All, When i send a mail through creat appointment using RTC. DAte and time which the user gets in his mail are different then what i have mentioned in create appointment mail. Is there any way to change the instant messening layout. I want to incr

  • Tiff images again.....

    I need to place TIFF images in a Forte Object to display on a client window. Does anyone have any tips or code that you would be willing to share that can help me do that. I checked with Forte the other day and found they do not support the TIFF form