Custom RepaintManager can't support true double-buffering?

RepaintManager doesn't provide a way to set bufferStrategyType. Custom RepaintManager can't support true double-buffering and 'gray rect' problem again?

Well looking at the source code, I was wrong... nevermind

Similar Messages

  • Dragging a drawing when double-buffering

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

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

  • Can PCI 6031E handle multi-buffered data acquisition

    If so can anyone send me some instructions or LabView code. Thank you in advance.

    Greetings,
    The PCI-6031E can handle single or double buffered acquisitions. The two best sources for examples and instructions are LabVIEW itself and our web site. Go to the "Help -> Find Examples" pull-down menu in LabVIEW to search for shipping examples. Look in the folder "Hardware Input and Output -> DAQ -> Analog Input -> General." Here you will find many analog input examples. Specifically, you should pay attention to the ones with "buffered" in the title.
    In addition to LabVIEW itself you will find our web site's Developer Zone extremely useful.
    Development Library
    http://zone.ni.com/devzone/devzone.nsf/6ae7945502d89dea0625685500506e1f/4d58b1b80ec41ef70625683f006e1d6d?OpenDocument
    Regards,
    Justin Britten
    Applications Engineer
    Nati
    onal Instruments

  • Can i use double buffering with SCAN_Sequence_Setup and sample rate divisors?

    If possible I would like to use double buffering when acquiring multiple channels at different rates using SCAN_Sequence_Setup. What are the tricks to sizing the buffers, if any.
    PCI-MIO-16Xe-10 and PCI-6052E are the boards I'm writing for, using Borland C++ builder under Windows2000
    Thanks,
    Brady

    Hello;
    At this time, you can't set up a multiple Scan Rate for different channels at same DAQ board. But, you can set up your Sample Rate to the fastest required to acquire you fastest channel, and then discard the readings of the other channels and only take the values for the different channels at their theoretical rate.
    Hope this helps.
    Filipe

  • Can your DAQ cards do TRUE async buffered daq while Labview does other things?

    I need to perform analysis on and save aquired data while the DAQ card is simulataneously and independently performing another scan session, initiated by an external trigger. I've found what look to be virtual or pseudo asynchronous buffered daq functions, but is the 6034-E or any other DAQ card capable of true async buffered aquisition via DMA while Labview is executing other things separately?

    testy,
    Yes, you can acquire, analyze, and save data simultaneously. There are examples that illustrate this that ship with LabVIEW (Help > Find Examples). Any buffered data acquisition is capable of this. Once the buffered acquisition is setup it is going to continue to sample the channels specified and put the data into memory via DMA (if available). Inside the while loop of your program you will do a read which reads some data from memory and brings it into LabVIEW's memory. So if in this while loop you also do some analysis and stream to disk that isn't a problem as long as you call your read function fast enough that your buffer doesn't overflow (the buffer that your DAQ card is shoveling the DMA transferred data into). All of our DAQ boards use DMA (if a
    vailable) by default for data transfer.
    Ames
    Applications Engineering
    National Instruments

  • 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();

  • Printing JTable after turning off double buffering causing repaint problems

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

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

  • Speeding up FileIO - Double Buffered File Copy?

    We are trying to speed up file copy from disk to tape, and I need a little more speed. I have tried playing with the size of the buffer, but that isn't changing much (makeing it slower if anything).
    I'm trying to make a double buffered file copy and I can't figure out how to do it. I figured this would be a good place to get speed. Right now, my write is very simple:
    byte buffer = new buffer[8 * 1024 * 1024];
    FileInputStream in = new FileInputStream(srcFile);
    while(true) {
      int amountRead = in.read(buffer);
      if (amountRead == -1) { break; }
      write(buffer, 0, length);
    }So what i need to do it be able to read and write at the same time. So I was thinking that I could either make the write method a sperate thread, or some how make threaded buffers that read while the other is being writen. Has anyone tackled this problem before?
    If this isn't the right way to speed up File IO, can you let me know other ideas? Thanks in advance!
    Andrew

    Once again: I wish I could claim credit for these classes, but they were in fact posted a year or so ago by someone lese. If I had the name I would give credit.
    I've used these for two heavy-duty applications with never a problem.
    <code>
    package pipes;
    import java.io.IOException;
    import java.io.InputStream;
    * This class is equivalent to <code>java.io.PipedInputStream</code>. In the
    * interface it only adds a constructor which allows for specifying the buffer
    * size. Its implementation, however, is much simpler and a lot more efficient
    * than its equivalent. It doesn't rely on polling. Instead it uses proper
    * synchronization with its counterpart PipedOutputStream.
    * Multiple readers can read from this stream concurrently. The block asked for
    * by a reader is delivered completely, or until the end of the stream if less
    * is available. Other readers can't come in between.
    public class PipedInputStream extends InputStream {
    byte[] buffer;
    boolean closed = false;
    int readLaps = 0;
    int readPosition = 0;
    PipedOutputStream source;
    int writeLaps = 0;
    int writePosition = 0;
    * Creates an unconnected PipedInputStream with a default buffer size.
    * @exception IOException
    public PipedInputStream() throws IOException {
    this(null);
    * Creates a PipedInputStream with a default buffer size and connects it to
    * source.
    * @exception IOException It was already connected.
    public PipedInputStream(PipedOutputStream source) throws IOException {
    this(source, 0x10000);
    * Creates a PipedInputStream with buffer size <code>bufferSize</code> and
    * connects it to <code>source</code>.
    * @exception IOException It was already connected.
    public PipedInputStream(PipedOutputStream source, int bufferSize) throws IOException {
    if (source != null) {
    connect(source);
    buffer = new byte[bufferSize];
    * Return the number of bytes of data available from this stream without blocking.
    public int available() throws IOException {
    // The circular buffer is inspected to see where the reader and the writer
    // are located.
    return writePosition > readPosition ? // The writer is in the same lap.
    writePosition - readPosition : (writePosition < readPosition ? // The writer is in the next lap.
    buffer.length - readPosition + 1 + writePosition :
    // The writer is at the same position or a complete lap ahead.
    (writeLaps > readLaps ? buffer.length : 0)
    * Closes the pipe.
    * @exception IOException The pipe is not connected.
    public void close() throws IOException {
    if (source == null) {
    throw new IOException("Unconnected pipe");
    synchronized (buffer) {
    closed = true;
    // Release any pending writers.
    buffer.notifyAll();
    * Connects this input stream to an output stream.
    * @exception IOException The pipe is already connected.
    public void connect(PipedOutputStream source) throws IOException {
    if (this.source != null) {
    throw new IOException("Pipe already connected");
    this.source = source;
    source.sink = this;
    * Closes the input stream if it is open.
    protected void finalize() throws Throwable {
    close();
    * Unsupported - does nothing.
    public void mark(int readLimit) {
    return;
    * returns whether or not mark is supported.
    public boolean markSupported() {
    return false;
    * reads a byte of data from the input stream.
    * @return the byte read, or -1 if end-of-stream was reached.
    public int read() throws IOException {
    byte[] b = new byte[0];
    int result = read(b);
    return result == -1 ? -1 : b[0];
    * Reads data from the input stream into a buffer.
    * @exception IOException
    public int read(byte[] b) throws IOException {
    return read(b, 0, b.length);
    * Reads data from the input stream into a buffer, starting at the specified offset,
    * and for the length requested.
    * @exception IOException The pipe is not connected.
    public int read(byte[] b, int off, int len) throws IOException {
    if (source == null) {
    throw new IOException("Unconnected pipe");
    synchronized (buffer) {
    if (writePosition == readPosition && writeLaps == readLaps) {
    if (closed) {
    return -1;
    // Wait for any writer to put something in the circular buffer.
    try {
    buffer.wait();
    catch (InterruptedException e) {
    throw new IOException(e.getMessage());
    // Try again.
    return read(b, off, len);
    // Don't read more than the capacity indicated by len or what's available
    // in the circular buffer.
    int amount = Math.min(len,
    (writePosition > readPosition ? writePosition : buffer.length) - readPosition);
    System.arraycopy(buffer, readPosition, b, off, amount);
    readPosition += amount;
    if (readPosition == buffer.length) {
    // A lap was completed, so go back.
    readPosition = 0;
    ++readLaps;
    // The buffer is only released when the complete desired block was
    // obtained.
    if (amount < len) {
    int second = read(b, off + amount, len - amount);
    return second == -1 ? amount : amount + second;
    } else {
    buffer.notifyAll();
    return amount;
    package pipes;
    import java.io.IOException;
    import java.io.OutputStream;
    * This class is equivalent to java.io.PipedOutputStream. In the
    * interface it only adds a constructor which allows for specifying the buffer
    * size. Its implementation, however, is much simpler and a lot more efficient
    * than its equivalent. It doesn't rely on polling. Instead it uses proper
    * synchronization with its counterpart PipedInputStream.
    * Multiple writers can write in this stream concurrently. The block written
    * by a writer is put in completely. Other writers can't come in between.
    public class PipedOutputStream extends OutputStream {
    PipedInputStream sink;
    * Creates an unconnected PipedOutputStream.
    * @exception IOException
    public PipedOutputStream() throws IOException {
    this(null);
    * Creates a PipedOutputStream with a default buffer size and connects it to
    * <code>sink</code>.
    * @exception IOException It was already connected.
    public PipedOutputStream(PipedInputStream sink) throws IOException {
    this(sink, 0x10000);
    * Creates a PipedOutputStream with buffer size <code>bufferSize</code> and
    * connects it to <code>sink</code>.
    * @exception IOException It was already connected.
    public PipedOutputStream(PipedInputStream sink, int bufferSize) throws IOException {
    if (sink != null) {
    connect(sink);
    sink.buffer = new byte[bufferSize];
    * Closes the input stream.
    * @exception IOException The pipe is not connected.
    public void close() throws IOException {
    if (sink == null) {
    throw new IOException("Unconnected pipe");
    synchronized (sink.buffer) {
    sink.closed = true;
    flush();
    * Connects the output stream to an input stream.
    * @exception IOException The pipe is already connected.
    public void connect(PipedInputStream sink) throws IOException {
    if (this.sink != null) {
    throw new IOException("Pipe already connected");
    this.sink = sink;
    sink.source = this;
    * Closes the output stream if it is open.
    protected void finalize() throws Throwable {
    close();
    * forces any buffered data to be written.
    * @exception IOException
    public void flush() throws IOException {
    synchronized (sink.buffer) {
    // Release all readers.
    sink.buffer.notifyAll();
    * writes a byte of data to the output stream.
    * @exception IOException
    public void write(int b) throws IOException {
    write(new byte[] {(byte) b});
    * Writes a buffer of data to the output stream.
    * @exception IOException
    public void write(byte[] b) throws IOException {
    write(b, 0, b.length);
    * writes data to the output stream from a buffer, starting at the named offset,
    * and for the named length.
    * @exception IOException The pipe is not connected or a reader has closed
    * it.
    public void write(byte[] b, int off, int len) throws IOException {
    if (sink == null) {
    throw new IOException("Unconnected pipe");
    if (sink.closed) {
    throw new IOException("Broken pipe");
    synchronized (sink.buffer) {
         if (sink.writePosition == sink.readPosition &&
         sink.writeLaps > sink.readLaps) {
         // The circular buffer is full, so wait for some reader to consume
         // something.
         try {
         sink.buffer.wait();
         catch (InterruptedException e) {
         throw new IOException(e.getMessage());
         // Try again.
         write(b, off, len);
         return;
         // Don't write more than the capacity indicated by len or the space
         // available in the circular buffer.
         int amount = Math.min(len,
         (sink.writePosition < sink.readPosition ?
         sink.readPosition : sink.buffer.length)
    - sink.writePosition);
         System.arraycopy(b, off, sink.buffer, sink.writePosition, amount);
         sink.writePosition += amount;
         if (sink.writePosition == sink.buffer.length) {
         sink.writePosition = 0;
         ++sink.writeLaps;
         // The buffer is only released when the complete desired block was
         // written.
         if (amount < len) {
         write(b, off + amount, len - amount);
         } else {
         sink.buffer.notifyAll();
    </code>

  • Problem with Double Buffering and Swing

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

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

  • Double buffering still gives flickering graphics.

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

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

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

  • Double Buffering and Components

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

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

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

  • I am trying to write a double buffered data acquisition program using MFC and a callback function.

    i am trying to do a double buffer data acquisition using MFC application framework in Visual Studio.i want to use a callback function to notify when the buffer is half full.do you have some sample reference program that can help me?

    What DAQ board are you using? When you installed NI-DAQ you should have selected to install the support files for VC++. Then there will be several examples on how to do double buffered data acquisition.
    If you have already installed NI-DAQ 6.8 or higher and did not select to include the support files, you can run the NI-DAQ setup program and just add them. If you are using an older version, you will have to uninstall and reinstall.
    Once you have the support files, follow this path to the examples.
    >>Program Files>>National Instruments>>NI-DAQ>>Examaples>>Visual C>>
    If you are doing digital acquistion, goto the di folder, if you are doing analog acquisition goto the ai folder.
    As for the callback function, you can use the NI-DAQ function Config_DAQ_
    Event_Message with DAQEvent Type = 1, where N would equal half your buffer.
    Brian

  • Properly (?) Double Buffered Applet is really Choppy

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

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

Maybe you are looking for

  • Changes to Private Messaging Notifications

    Hi All After getting feedback from different forum members I have made a change to the Private Messaging (PM) email notifications.  You may not have known, but it is possible to set up an email alert to let you know when you get a private message.  S

  • Creating text in various languages

    I have a project where I have to sub-title a film in 7 different languages, including chinese and korean. Will I be able to use Livetype to construct the sub-titles in all the languages- in other words, will I or a suitably qualified person be able t

  • Report development/publishing workflow - best practices?

    Before starting to work with Crystal Reports Server, I saved my development reports on my local machine, checking them into Subversion for version control, and copying changed reports up to the public share for general use. However, since installing

  • IPad 3 Settings crashes when trying to enable iCloud Calendar

    Hi all, Being a Apple fan, I am getting peeved by lack of quality. I bought the new iPad on launch day in March and the Calendar app has rarely worked. Matter of fact it crashed almost constantly. To try and fix this issue, I had turned off iPad > Se

  • Calling struts actions between the two Web projects

    I don't know if it's the right forum for this question. Let's say I have two Web projects: MyProjectWeb and OtherProjectWeb. Each of them has they own struts-config.xml configuration and each of them has they own Web Deployment Descriptor (web.xml):