Speed of Swing versus double buffered AWT

Hello
I've noticed that drawing in a JPanel.paintComponent() takes about 4 times longer than drawing into an offscreen image in AWT Canvas.paint()
Essential code excerpts follow
// SWING, takes about 400 millis on my machine
public void paintComponent(Graphics g) {
g.setColor(Color.red);
long startTime = System.currentTimeMillis();
for (int i = 0; i < 10000; i++)
g.draw3DRect((int) (Math.random() * 200), 20, 30, 40, true);
long endTime = System.currentTimeMillis();
System.out.println("paintComponent() took " + (endTime - startTime) + " millis");
// AWT, takes about 100 millis on same machine
public void paint(Graphics g) {
if (offscreenGraphics == null || offscreenImage == null) {
offscreenImage = createImage(getWidth(), getHeight());
offscreenGraphics = offscreenImage.getGraphics();
long startTime = System.currentTimeMillis();
if (offscreenGraphics != null) {
offscreenGraphics.setColor(Color.red);
for (int i = 0; i < 10000; i++)
offscreenGraphics.draw3DRect((int) (Math.random() * 200), 20, 30, 40, true);
g.drawImage(offscreenImage, 0, 0, this);
long endTime = System.currentTimeMillis();
System.out.println("paint() took " + (endTime - startTime) + " millis");
Note that I also tried drawLine() instead of draw3DRect() and experienced similar results
Can someone explain why doing this in Swing is so slow?
I'd hoped to take advantage of Swing's double buffering, but I ended up using the same old offscreen image technique in Swing.
Nick Didkovsky

Silly question, but did you turn on double buffering or extend a Swing component which has it on by default?
Not all of them do.
: jay

Similar Messages

  • 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

  • Swings auto double buffer

    Swing has double buffering by default, but i still see flicker.
    whay does it flicker it double buffering is turned on.

    Well ive eliminated it now by using....
    <code>
    public void paint(Graphics g){
         update(g);
    public void update(Graphics g){
         // Draws the buffered image to the screen.
         g.drawImage(imageOffScreen, xPos, 0, this);
    </code>
    ..... and doing my drawing in another Graphicsoject.

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

  • 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

  • Alternative to Double-Buffered Canvas

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

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

  • Double buffering still gives flickering graphics.

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

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

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

  • 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

  • Sprite animation with double buffering

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

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

  • Panel refreshing and double buffering

    Hi all swing experts
    Could any one solve the problem.I have an application,which is having a JSplit pane.
    On the left of the JSplit pane , there is a tree. When u click a node from the tree
    that will be selected and you can place that node into the right side panel.
    And the same way you can click an another node (redirection or sink) and drop into the
    panel.you can draw a line by clicking the source and the sink / or redirection.
    The line is getting drawn dynamically by getting the x,y coordinates of the node.
    once the line is drawn am storing the line into vector, since this is getting drawn
    dynamically once if i minimize and maxmize it will disappear.
    For avoiding this am trying to redraw the old line from the vector when the window
    is getting activated, here the problem starts it draws the line but the line
    is getting disappeared immly.
    HOW DO I SOLVE THIS?
    is it possible to solve this problem with double buffering tech? if so how?
    PL HELP.
    Software - Visual Tool
    Last Modified -7/23/01
    sami
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.border.TitledBorder;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.plaf.FontUIResource;
    import javax.swing.tree.*;
    import java.lang.System;
    import java.net.*;
    import java.awt.image.*;
    import javax.swing.event.*;
    public class CompTree extends JFrame implements TreeSelectionListener,WindowListener{      
    // Swing components declarations     
         public JSplitPane jSplitPane1,jSplitPaneTop;
         public JScrollPane treeScrollPane,splitScrollPane;     
    public JTree mainTree,jtree ;
    public static DefaultMutableTreeNode topchildnode1, topchildnode2, topchildnode3,toptreenode;
    DrawPanel dp = new DrawPanel();
         public int i=0;
         public int j=0;
         public int flag = 1 ;
         public String var,S,R,D;
    Frame fr = new Frame("GUI TOOL");
    public CompTree()
         File nFile = null ;     
         mainTree = DrawTree(nFile,"N") ;
         mainTree.updateUI();
         mainTree.setBackground(new Color(105,205,159));     
              // Tree is getting added into scroll pane
         treeScrollPane = new JScrollPane(mainTree);
              treeScrollPane.setVerticalScrollBarPolicy(javax.swing.JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    treeScrollPane.setHorizontalScrollBarPolicy(javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
              splitScrollPane = new JScrollPane();
              splitScrollPane.setViewportView(dp.panel1);          
              splitScrollPane.setVerticalScrollBarPolicy(javax.swing.JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    splitScrollPane.setHorizontalScrollBarPolicy(javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    jSplitPane1 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,treeScrollPane,splitScrollPane);          
         jSplitPane1.setOneTouchExpandable(true);
         jSplitPane1.setContinuousLayout(true);
    jSplitPane1.addComponentListener(new ComponentAdapter(){
              public void componentResized(ComponentEvent e) {      
                   System.out.println("Componenet resized");
              flag = 1;
              paint(dp.panel1.getGraphics());          
    //Provide minimum sizes for the two components in the split pane
    Dimension minimumSize = new Dimension(150,75);
              splitScrollPane.setMinimumSize(minimumSize);
    //Provide a preferred size for the split pane
    jSplitPane1.setPreferredSize(new Dimension(700, 500));
              //setContentPane(jSplitPane1);
              fr.add(jSplitPane1);
              fr.setSize(700,500);
              fr.setVisible(true);          
              fr.addWindowListener(this);     
    public void windowActivated(WindowEvent we){
         System.out.println("activated");
         dp.draw();
    public void windowClosed(WindowEvent we){System.out.println("closed");}
    public void windowIconified(WindowEvent we){System.out.println("iconified");}
    public void windowDeiconified(WindowEvent we){
         dp.draw();
         System.out.println("deiconified");
    public void windowDeactivated(WindowEvent we){System.out.println("deactivated");}
    public void windowOpened(WindowEvent we){
         dp.repaint();
         System.out.println("opened");
    public void windowClosing(WindowEvent we){
         System.exit(0);
         System.out.println("closing");
         public void valueChanged(TreeSelectionEvent e) {
              DefaultMutableTreeNode node = (DefaultMutableTreeNode)
              mainTree.getLastSelectedPathComponent();     
              String strRootNode = "" ;
              try{
                   Object rootNode = node.getRoot();          
                   strRootNode = rootNode.toString() ;
              catch(Exception eRoot)
                   System.out.println("Error in geting Root Node");
              if (node == null) return;
              Object nodeInfo = node.getUserObject();          
              TreeNode ParentNode = node.getParent();               
              final String strParentName = node.toString() ;
                   if (strParentName.equals("Source"))
              System.out.println("Before source");     
              var = "S";
              System.out.println("This is source");
              else if (strParentName.equals("Redirection"))
    var ="R";
              else if (strParentName.equals("Sink") )
                   var ="D";
              else
                   if ( strRootNode != strParentName){
         public JTree DrawTree( File file, String strIsValid)
                   jtree = new JTree();
                   toptreenode = new DefaultMutableTreeNode("Start");
                   topchildnode1 = new DefaultMutableTreeNode("Source");
                   topchildnode2 = new DefaultMutableTreeNode("Sink");
                   topchildnode3 = new DefaultMutableTreeNode("Redirection");
                   toptreenode.add(topchildnode1);
                   toptreenode.add(topchildnode2);
                   toptreenode.add(topchildnode3);
                   jtree.putClientProperty("JTree.lineStyle", "Angled");
                   DefaultTreeModel defaulttreemodel = new DefaultTreeModel(toptreenode);
                   jtree.setModel(defaulttreemodel);
                   DefaultTreeSelectionModel defaulttreeselectionmodel = new DefaultTreeSelectionModel();
                   defaulttreeselectionmodel.setSelectionMode(1);
                   jtree.setSelectionModel(defaulttreeselectionmodel);
                   jtree.addTreeSelectionListener(this);
                   jtree.setEditable(true);
                   return jtree;      
    public static void main(String args[]){
         CompTree ct = new CompTree();
         * This class contains all the component related to panel 1
         * this can be used for .....
    public class DrawPanel extends JPanel implements ActionListener,
         ComponentListener,MouseListener,KeyListener{
         public JRadioButton uniRadio,multiRadio,show;
         public JButton sBut,rBut,dBut;
         public int flag = 1 ;
         public int Radio = 1;
         public boolean sIndicator = true;
         public boolean rIndicator = true;
         public boolean isDestSelected = false;
         public boolean isDestFirstTime = true;
    public int x1 = 0 ;
         public int y1 = 0 ;
         public int x2 = 0 ;
         public int y2 = 0;
         public int x3 = 0;
         public int y3 = 0;
         public int k=0;
         public int l = 40;
    public int b = 40;     
         public String connection1,connection2,connection3,destination1,destination2;
         public int locX;
         public int locY;
    public JPanel panel1 = new JPanel ();      
    public JPanel panel2 = new JPanel ();     
         Vector lines = new Vector();
         Vector colors = new Vector();
         Vector obj = new Vector();
    Vector source = new Vector();
         Vector loc = new Vector();
         BasicStroke stroke = new BasicStroke(2.0f);
    Icon compImage = new ImageIcon("network1.gif"); //new
    Icon workImage = new ImageIcon("tconnect02.gif");
    Icon lapImage = new ImageIcon("server02.gif");
         public DrawPanel(){
         am adding radio button for checking the mode unicast and broad cast mode -- new
    uniRadio = new JRadioButton("Unicast Mode");
    uniRadio.setMnemonic(KeyEvent.VK_B);
    uniRadio.setSelected(true);
    multiRadio = new JRadioButton("Broadcast Mode");
    multiRadio.setMnemonic(KeyEvent.VK_C);
    show = new JRadioButton("show Panel");
    show.setMnemonic(KeyEvent.VK_C);
         ButtonGroup group = new ButtonGroup();
    group.add(uniRadio);
    group.add(multiRadio);
              group.add(show);
         /*     Border border = ButtonGroup.getBorder();
              Border margin = new EmptyBorder(10,10,10,10);
              ButtonGroup.setBorder(new CompoundBorder(border,margin)); */
              uniRadio.addActionListener(this);
         multiRadio.addActionListener(this);
              show.addActionListener(this);
    panel1.add(uniRadio);
              panel1.add(multiRadio);
              panel1.add(show);
              uniRadio.setBounds(150,15,100,40);
              multiRadio.setBounds(260,15,120,40);
              show.setBounds(390,15,100,40);
              uniRadio.setBackground(new Color(105,200,205));
              multiRadio.setBackground(new Color(105,200,205));
              show.setBackground(new Color(105,200,205));
              /*****************PANEL 1*********************/
              panel1.setLayout(null);
    panel1.setBounds(new Rectangle(0,0,400,400));
              panel1.setBackground(new Color(105,100,205));
              panel1.addComponentListener(this);
              panel1.addMouseListener(this);      
         public void sourceObject(String name)
    sBut = new JButton(compImage);
         panel1.add(sBut);     
         sBut.setMnemonic(KeyEvent.VK_F);
         sBut.setBounds(new Rectangle(locX,locY,l,b));     
         sBut.addActionListener(this);
         sBut.addMouseListener(this);
         sBut.addKeyListener(this);
    System.out.println("am inside the source object") ;
         sBut.setBackground(new Color(105,100,205));
         System.out.println("key number" +sBut.getMnemonic());
         System.out.println("MY LOCATION : SBUT : "+ sBut.getLocation());
         public void redirectionObject(String name)
         rBut = new JButton(workImage);
         panel1.add(rBut);
         rBut.setBounds(new Rectangle(locX,locY,l,b));     
    rBut.addActionListener(this);
         rBut.addMouseListener(this);
         rBut.addKeyListener(this);
         rBut.setBackground(new Color(105,100,205));
    System.out.println("am inside the redirection :" + j) ;
    System.out.println("MY LOCATION : RBUT : "+ rBut.getLocation());          
    public void destinationObject(String name){     
         dBut = new JButton(lapImage);
         panel1.add(dBut);     
         dBut.setBackground(new Color(105,100,205));
    System.out.println("am inside the destination object") ;     
    dBut.setBounds(new Rectangle(locX,locY,l,b));                    
         System.out.println("am inside the destination:" + j) ;
         dBut.addActionListener(this);
         dBut.addMouseListener(this);
         dBut.addKeyListener(this);
         System.out.println("MY LOCATION : DBUT : "+ dBut.getLocation());           
    public void paintComponent(Graphics g){
    super.paintComponent(g);
         System.out.println("inside paint");
         Graphics2D g2 = (Graphics2D) g;
    g2.setStroke(stroke);
    if(flag == 1){
         /* this is for drawing current line, this will be drawn when component event happens */
              g.setColor(getForeground());
    System.out.println("inside flag");
    int np = lines.size();
                        System.out.println("Total number of lines present the buffer to draw :" + np);
                             for (int I=0; I < np; I++) {                       
         Rectangle p = (Rectangle)lines.elementAt(I);
                        g2.setColor((Color)colors.elementAt(I));
                             System.out.println("width" + p.width);
                             g2.setColor(Color.red);
                        //     g2.setPaint(p.x,p.y,p.width,p.height);
                             g2.drawLine(p.x,p.y,p.width,p.height);                         
                             System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
                             System.out.println(obj.elementAt(I));
                             System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
                             System.out.println(p.x +"," +","+ p.y + ","+ ","+ p.width+ "," + ","+ p.height);
    flag = -1;
    }else if(flag == -1){
         if(x1 != 0 && y1 != 0 && x2 != 0 && y2 != 0 ){
    connection1 = "source to redirection";
    g2.setColor(Color.red);
         g2.drawLine(x1,y1,x2,y2);          
         lines.addElement(new Rectangle(x1,y1,x2,y2));
         colors.addElement(getForeground());
         obj.addElement(connection1);
         x1 = 0 ;y1 = 0 ;
         x2 = 0 ;y2 = 0 ;
    else if (x2 != 0 && y2 != 0 && x3 != 0 && y3 != 0 )
              connection2 = "Redirection to Destination";
              g2.setColor(Color.green);
                   g2.drawLine(x2,y2,x3,y3);                    
    colors.addElement(getForeground());
                   lines.addElement(new Rectangle(x2,y2,x3,y3));               
                   obj.addElement(connection2);
                   x2 = 0; y2 = 0 ;
                   x3 = 0 ; y3 = 0 ;                    
    else if (x1 != 0 && y1 != 0 && x3 != 0 && y3 != 0)
                   connection3 = "Source to Destination";
                   g2.setColor(Color.red);
                   g2.drawLine(x1,y1,x3,y3);                    
    colors.addElement(getForeground());
                   lines.addElement(new Rectangle(x1,y1,x3,y3));                              
                   obj.addElement(connection3);
                        x1 = 0; y1 = 0 ;
                        x3 = 0 ; y3 = 0 ;                    
                        /*     Image offscreen = panel1.createImage(400,400);
              Graphics og = offscreen.getGraphics();
         og.drawLine(200,200,500,500);
              g.drawImage(offscreen,0,0,null); */
    // Component Listener's method
    public void componentHidden(ComponentEvent e) { 
    if(e.getSource().equals(panel1)){System.out.println("Componenet Hidden");}
              System.out.println("Componenet Hidden");
    public void componentMoved(ComponentEvent e) {
              System.out.println("Componenet moved");
              draw();
    public void componentResized(ComponentEvent e) {      
              System.out.println("Componenet resized");
              flag = 1;
              paintComponent(panel1.getGraphics());
    public void componentShown(ComponentEvent e) {     
              System.out.println("Componenet Shown");
    // Mouse Listerner's Method
         public void mouseClicked(MouseEvent me){
    if (me.getSource().equals(panel1))
              System.out.println("inside mouse clicked");
                        if(var == "S"){
    the boolean sIndicator will allow the usage of source object only once
         This is the case for both unicast and multi cast.It has been restricted
         to single use.
                             if (sIndicator){
                             System.out.println("inside mouse clicked");
                        System.out.println("locX" + locX);
                        locX = me.getX();
    locY = me.getY();
                   sourceObject("Source");
                             sIndicator = false;
                        }else{}
              }else if (var == "R")
    if(rIndicator){
    if(!isDestSelected){
    System.out.println("redirection" + locX);
    locX = me.getX();
    locY = me.getY();
                   redirectionObject("Redirection");
                   rIndicator = false;
                   }else{}
    } else{}
              }else if(var == "D"){
              if(Radio == 1 && isDestSelected == false){
              System.out.println("Destination -- uni cast mode" + locX);
    locX = me.getX();
    locY = me.getY();
                   destinationObject("Sink");
              isDestSelected = true;
              } else if (Radio == 2)
                                  System.out.println("Destination -- Multicast mode" + locX);
                                  locX = me.getX();
                                  locY = me.getY();
                                  destinationObject("Sink");
                                  isDestSelected = true;                    
         public void mousePressed(MouseEvent me){System.out.println("am inside mouse pressed"); }
         public void mouseReleased(MouseEvent me){
              System.out.println("am inside mouse released");
              paintComponent(panel1.getGraphics());
         public void mouseEntered(MouseEvent me){}
         public void mouseExited(MouseEvent me){}
    // key Listener
    public void keyReleased(KeyEvent e) {        
                        Component compo =(JButton)e.getSource();                               
                             if (e.getKeyChar() == e.VK_DELETE){                         
                             remove(compo);
              public void keyTyped(KeyEvent e) {}
              public void keyPressed(KeyEvent e){}
    public void remove(Component comp){          
    System.out.println("inside delete key" );                         
         panel1.remove(comp);
         panel1.repaint();     
         public void draw(){
              super.paint(panel1.getGraphics());
              System.out.println("inside draw");
              flag = 1;
              paintComponent(panel1.getGraphics());     
         public void actionPerformed(ActionEvent e)
                             if(e.getSource().equals(sBut)){
                                  System.out.println("am s button");                
                                  x1 = sBut.getX() + l;
                                  y1 = sBut.getY() + (b/2);
                             else if(e.getSource().equals(rBut)){
                                  System.out.println("am r button");               
                                  x2 = rBut.getX() ;
                                  y2 = rBut.getY()+ b/2;
                                  System.out.println("x2 : " + x2 + "y2 :" +y2 );
                             else if(e.getSource().equals(dBut)){
                                  System.out.println("am d button");                
                                  x3 = dBut.getX();
                                  y3 = dBut.getY()+ b/2;
                             else if (e.getSource().equals(uniRadio)){
                                  System.out.println("uni radio");
                                  Radio = 1 ;
                             } else if (e.getSource().equals(multiRadio)){
                                       System.out.println("multi radio");
                                       Radio = 2;
                             } else if (e.getSource().equals(show)){            
                                  System.out.println("inside show");
    *********************************************

    ok
    i don't take a long time tracing your code, but i think u have to overwrite the repaint methode so it 's call the methode which will paint the line each time.
    hope this will help!

  • Double Buffering Problem in html

    My double buffering works in my IDE, but not when embedded in html.
    import javax.swing.*;
    import java.applet.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.util.*;
    class Brick
        public int x,y;   
        public Brick(int x,int y) {this.x = x;this.y = y;}
    class Ball
        public int x,y,a,b;
        public Ball(int x, int y) {this.x = x;this.y = y;}
    public class Pong2 extends JApplet implements MouseListener, MouseMotionListener, Runnable, KeyListener
        long tm = System.currentTimeMillis();
        int delay;
        int a1=0,b1=0,c1=0,d1=0;
        int dead;
        int ranB1,ranB2;
        boolean pauseB = false;
        boolean starttext = true;
        int ani = 0;
        String stringWin;
        Graphics offscreen;Image image;
        private final int INIT_ACTIVE = 0;
        private final int INTRO_ACTIVE = 1;
        private final int GAME1_ACTIVE = 2;
        private final int GAME2_ACTIVE = 3;
        private final int GAME3_ACTIVE = 4;
        private int r1,r2,r3,r4,r5,starter=0,win=0,own=0;
        private int gameflag;
        private boolean player = true,moveB = true,thisB = true,timerB = true;
        private boolean drawB = true;
        private int counte=0;
        private int time = -2;
        private int movecheck1; int movecheck2;int movecheck3;int movecheck4;
        private int c;
        private int god = 0;
        private int tempx1, tempy1,tempx2,tempy2;
        private int pause = 2, resume = 0;
        private int ran, ran2,ran3,ran4;
        private int yCheck1,yCheck2,yCheck3,yCheck4,xCheck1,xCheck2,xCheck3,xCheck4;
        private int begin = 0;
        private int counter = 0, colorChange =0;
        private Brick brick[] = new Brick[4];
        private Ball ball[] = new Ball[2];
        private Ball ball2[] = new Ball[8];
        private int cons1 = 0,cons2 = 0,cons3=0,cons4=0;
        private int score1=10, score2=10,score3=10,score4=10;
        private Thread t;
        private Font font;
        private AudioClip match,teleport,headshot, ballbounce, dkill,humiliation,one,two,three,fight,prepare;   
        public Image paddle3,paddle4,rarrow,dbuffer,paddle,paddle2,bricks,blood,title,edge,m_imgOffScr;
        private Graphics dbuffer_gfx,m_gOffScr,dbg;
        private Color Color1 = new Color(255,255,255);
        private Color sColor3 = new Color(139,80,14);
        private Color sColor2 = new Color(0,255,0);
        private Color sColor4 = new Color(255,255,0);
        private Polygon poly1 = new Polygon();Polygon poly2 = new Polygon(); 
        private Polygon poly3 = new Polygon();Polygon poly4 = new Polygon();
        private boolean p1Dead=false, p2Dead=false, p3Dead=false, p4Dead=false;
        private int ranLoc, winner;
        public void initgame()
            poly1.addPoint(0,0);poly1.addPoint(0,125);poly1.addPoint(125,0);
            poly2.addPoint(0,650);poly2.addPoint(125,650);poly2.addPoint(0,525);
            poly3.addPoint(650,0);poly3.addPoint(650,125);poly3.addPoint(525,0);
            poly4.addPoint(650,650);poly4.addPoint(650,525);poly4.addPoint(525,650);
            for (int j = 0; j < ball.length; j++){ball[j] = new Ball(325,325);}
            brick[0] = new Brick(25,285);
            brick[1] = new Brick(615,285);
            brick[2] = new Brick(285,25);
            brick[3] = new Brick(285,615);
            yCheck1 = brick[0].y; yCheck2 = brick[1].y; yCheck3 = brick[2].y; yCheck4 = brick[3].y;
            xCheck1 = brick[0].x; xCheck2 = brick[1].x; xCheck3 = brick[2].x; xCheck4 = brick[3].x;
            if(player)
            for (int n = 0; n<8; n++)
                r1 = (int)(Math.random() * 600)+10;r2 = (int)(Math.random() * 600)+10;
                ball2[n] = new Ball(r1,r2);
                if (n == 0||n==4) {ball2[n].a = 3; ball2[n].b = 3;}if (n == 1||n==5) {ball2[n].a = -3; ball2[n].b = 3;}
                if (n == 2||n==6) {ball2[n].a = 3; ball2[n].b = -3;}if (n == 3||n==7) {ball2[n].a = -3; ball2[n].b = -3;}           
            player = false;
        public void init()
            gameflag = INIT_ACTIVE;
            setSize(650,725);
            requestFocus();      
            Font font = new Font ("Arial", Font.BOLD,50);
            paddle = getImage(getCodeBase(), "paddle.jpg");
            paddle2 = getImage(getCodeBase(), "paddle2.jpg");
            paddle3 = getImage(getCodeBase(), "paddle3.jpg");
            paddle4 = getImage(getCodeBase(), "paddle4.jpg");
            bricks = getImage(getCodeBase(), "bricks.jpg");
            blood = getImage(getCodeBase(), "blood.jpg");
            title = getImage(getCodeBase(), "title.jpg"); 
            headshot = getAudioClip(getCodeBase(), "headshot2.wav");
            ballbounce = getAudioClip(getCodeBase(), "ir_begin.wav");
            humiliation = getAudioClip(getCodeBase(), "humiliation.wav");
            prepare = getAudioClip(getCodeBase(), "prepare.wav");
            teleport = getAudioClip(getCodeBase(), "teleport.wav");
            match = getAudioClip(getCodeBase(), "matchwin.wav");
            dbuffer=createImage(getSize().width,getSize().height);
            dbuffer_gfx=dbuffer.getGraphics();
            initgame();
            addMouseListener(this);
            addMouseMotionListener(this);
            addKeyListener(this);
        public void start()
            Thread t = new Thread(this);
            t.start();
            new Thread(pMovement).start();                       
        public void stop()
            t.yield();
            t = null;
        public void update (Graphics g)
            paint(dbuffer_gfx);
            g.drawImage(dbuffer,0,0,this);
        public void PaintIntro(Graphics g)
            g.setColor(Color.white);
            g.fillRect(0,0,650,725);
            g.setColor(Color.black);
            for(int wa = 0;wa<8;wa++)
            g.fillOval(ball2[wa].x,ball2[wa].y,10,10);
            g.drawImage(title,100,100,this);
            g.setFont(new Font("Arial", Font.BOLD,20));
            g.drawString("Written By Alec Parenzan",200,200);
            g.setFont(new Font("Arial", Font.BOLD,14));
            if (colorChange==0)g.setColor(Color.blue);
            g.drawString("4 Player Game",275,430);
            g.setColor(Color.black);
            if (colorChange==1)g.setColor(Color.blue);
            g.drawString("2 Player Game",275,450);
            g.setColor(Color.black);
            if (colorChange==2)g.setColor(Color.blue);
            g.drawString("1 Player Game",275,470);
        public void PaintGame1 (Graphics g)
            g.setColor(Color.black);
            g.drawImage(blood,0,0,650,650,this);
            if(p1Dead==false && own>0 )g.drawImage(paddle3,brick[0].x,brick[0].y,10,80,this);
            if(p2Dead==false&& own>0)g.drawImage(paddle,brick[1].x,brick[1].y,10,80,this);
            if(p3Dead==false&& own>0)g.drawImage(paddle2,brick[2].x,brick[2].y,80,10,this);
            if(p4Dead==false&& own>0)g.drawImage(paddle4,brick[3].x,brick[3].y,80,10,this);
            g.fillPolygon(poly1);g.fillPolygon(poly2);g.fillPolygon(poly3);g.fillPolygon(poly4);
            g.setColor(Color.white);
            g.drawPolygon(poly1);g.drawPolygon(poly2);g.drawPolygon(poly3);g.drawPolygon(poly4);
            g.setColor(Color.black);
            if(begin==1 && drawB)
            {g.fillOval(ball[0].x,ball[0].y,10,10);g.fillOval(ball[1].x,ball[1].y,10,10);}
            g.drawImage(bricks,1,650,650,75,this);
            //score
            g.setFont(new Font("Comic Sans MS", Font.ITALIC,50));
            if(own>0){
                g.setColor(sColor2);g.drawString(Integer.toString(score1),50,705);
                g.setColor(Color.orange);g.drawString(Integer.toString(score2),150,705);
                g.setColor(Color.blue);g.drawString(Integer.toString(score3),440,705);
                g.setColor(sColor3);g.drawString(Integer.toString(score4),540,705);}
            //painting gui
            if (starttext) {g.setColor(Color.black);
                g.setFont(new Font("Arial", Font.ITALIC,30));g.drawString("Click START to Begin",175,325);}
            g.setColor(Color1);
            g.setFont(new Font("Arial", Font.BOLD,30));
            if(pause ==1 && begin>0)g.drawString("RESUME",270,700);
            else if(begin==0)g.drawString("START",270,700);
            else if(begin>=1 && begin<=2 && pause==0){g.drawString("PAUSE",270,700);}    
            //start
            g.setFont(font);g.setColor(Color.black);
            if(win ==1){if(winner==1)g.setColor(Color.green);else if(winner==2)g.setColor(Color.orange);
                else if(winner==3)g.setColor(Color.blue);else if(winner==4)g.setColor(sColor3);           
                g.drawString(stringWin,245,325);}
            g.setColor(Color.black);
            if (time == 1)g.drawString("3",300,325);
            else if (time==2)g.drawString("2",300,325);
            else if (time==3)g.drawString("1",300,325);          
        public void PaintGame2(Graphics g)
            g.setColor(Color.black);
            g.drawImage(blood,0,0,650,650,this);
            if(p1Dead==false && own>0 )g.drawImage(paddle3,brick[0].x,brick[0].y,10,80,this);
            if(p2Dead==false&& own>0)g.drawImage(paddle,brick[1].x,brick[1].y,10,80,this);
            g.fillPolygon(poly1);g.fillPolygon(poly2);g.fillPolygon(poly3);g.fillPolygon(poly4);
            g.setColor(Color.white);
            g.drawPolygon(poly1);g.drawPolygon(poly2);g.drawPolygon(poly3);g.drawPolygon(poly4);
            g.setColor(Color.black);
            if(begin==1 && drawB)
            {g.fillOval(ball[0].x,ball[0].y,10,10);g.fillOval(ball[1].x,ball[1].y,10,10);}
            g.drawImage(bricks,1,650,650,75,this);
            //score
            g.setFont(new Font("Comic Sans MS", Font.ITALIC,50));
            if(own>0){
                g.setColor(sColor2);g.drawString(Integer.toString(score1),50,705);
                g.setColor(Color.orange);g.drawString(Integer.toString(score2),540,705);}
            //painting gui
            if (starttext) {g.setColor(Color.black);
                g.setFont(new Font("Arial", Font.ITALIC,30));g.drawString("Click START to Begin",175,325);}
            g.setColor(Color1);
            g.setFont(new Font("Arial", Font.BOLD,30));
            if(pause ==1 && begin>0)g.drawString("RESUME",270,700);
            else if(begin==0)g.drawString("START",270,700);
            else if(begin>=1 && begin<=2 && pause==0){g.drawString("PAUSE",270,700);}    
            //start
            g.setFont(font);g.setColor(Color.black);
            if(win ==1){if(winner==1)g.setColor(Color.green);else if(winner==2)g.setColor(Color.orange);}
            g.setColor(Color.black);
            if (time == 1)g.drawString("3",300,325);
            else if (time==2)g.drawString("2",300,325);
            else if (time==3)g.drawString("1",300,325);     
        //paint graphics
        public void paint(Graphics g)
                g.setColor(Color.WHITE);
                g.fillRect(0,0,500,500);
                g.setColor(Color.BLACK);
            if (gameflag == INIT_ACTIVE)
                g.setColor(Color.black);
                g.fillRect(0,0,getSize().width,getSize().height);
                g.setColor(Color.white);
                g.drawString("Loading...",getSize().width/2, getSize().height/2);
            if (gameflag == INTRO_ACTIVE){PaintIntro(g);}
            if (gameflag == GAME1_ACTIVE){PaintGame1(g);} 
            if (gameflag == GAME2_ACTIVE || gameflag == GAME3_ACTIVE){PaintGame2(g);}
        public void paddlephys()
            for(int j =0; j < 2;j++)
                //P1
                if(p1Dead==false&&ball[j].x-4<=xCheck1 && ball[j].x<=xCheck2 && begin==1)
                    if (ball[j].y>=yCheck1&&ball[j].y<=yCheck1+12) {ball[j].a=2;ball[j].b=-4;ballbounce.play();}
                    else if (ball[j].y>=yCheck1+13&&ball[j].y<=yCheck1+25) {ball[j].a=3;ball[j].b=-3;ballbounce.play();}
                    else if (ball[j].y>=yCheck1+26&&ball[j].y<=yCheck1+39) {ball[j].a=4;ball[j].b=-2;ballbounce.play();}
                    else if (ball[j].y>=yCheck1+40&&ball[j].y<=yCheck1+53) {ball[j].a=4;ball[j].b=2;ballbounce.play();}
                    else if (ball[j].y>=yCheck1+54&&ball[j].y<=yCheck1+66) {ball[j].a=3;ball[j].b=3;ballbounce.play();}
                    else if (ball[j].y>=yCheck1+67&&ball[j].y<=yCheck1+79) {ball[j].a=2;ball[j].b=4;ballbounce.play();}
                //P2
                if(p2Dead==false&&ball[j].x>=xCheck2 && ball[j].x<=xCheck2+5 && begin==1)
                    if (ball[j].y>=yCheck2&&ball[j].y<=yCheck2+12) {ball[j].a=-2;ball[j].b=-4;ballbounce.play();}
                    else if (ball[j].y>=yCheck2+13&&ball[j].y<=yCheck2+25) {ball[j].a=-3;ball[j].b=-3;ballbounce.play();}
                    else if (ball[j].y>=yCheck2+26&&ball[j].y<=yCheck2+39) {ball[j].a=-4;ball[j].b=-2;ballbounce.play();}
                    else if (ball[j].y>=yCheck2+40&&ball[j].y<=yCheck2+53) {ball[j].a=-4;ball[j].b=2;ballbounce.play();}
                    else if (ball[j].y>=yCheck2+54&&ball[j].y<=yCheck2+66) {ball[j].a=-3;ball[j].b=3;ballbounce.play();}
                    else if (ball[j].y>=yCheck2+67&&ball[j].y<=yCheck2+79) {ball[j].a=-2;ball[j].b=4;ballbounce.play();}
                //P3
                if(p3Dead==false&&ball[j].y>=yCheck3-5 && ball[j].y<=yCheck3 && begin==1)
                    if (ball[j].x>=xCheck3&&ball[j].x<=xCheck3+12) {ball[j].a=-4;ball[j].b=2;ballbounce.play();}
                    else if (ball[j].x>=xCheck3+13&&ball[j].x<=xCheck3+25) {ball[j].a=-3;ball[j].b=3;ballbounce.play();}
                    else if (ball[j].x>=xCheck3+26&&ball[j].x<=xCheck3+39) {ball[j].a=-2;ball[j].b=4;ballbounce.play();}
                    else if (ball[j].x>=xCheck3+40&&ball[j].x<=xCheck3+53) {ball[j].a=2;ball[j].b=4;ballbounce.play();}
                    else if (ball[j].x>=xCheck3+54&&ball[j].x<=xCheck3+66) {ball[j].a=3;ball[j].b=3;ballbounce.play();}
                    else if (ball[j].x>=xCheck3+67&&ball[j].x<=xCheck3+79) {ball[j].a=4;ball[j].b=2;ballbounce.play();}
                //P4
                if(p4Dead==false&&ball[j].y>=yCheck4 && ball[j].y<=yCheck4+5 && begin==1)
                    if (ball[j].x>=xCheck4&&ball[j].x<=xCheck4+12) {ball[j].a=-4;ball[j].b=-2;ballbounce.play();}
                    else if (ball[j].x>=xCheck4+13&&ball[j].x<=xCheck4+25) {ball[j].a=-3;ball[j].b=-3;ballbounce.play();}
                    else if (ball[j].x>=xCheck4+26&&ball[j].x<=xCheck4+39) {ball[j].a=-2;ball[j].b=-4;ballbounce.play();}
                    else if (ball[j].x>=xCheck4+40&&ball[j].x<=xCheck4+53) {ball[j].a=2;ball[j].b=-4;ballbounce.play();}
                    else if (ball[j].x>=xCheck4+54&&ball[j].x<=xCheck4+66) {ball[j].a=3;ball[j].b=-3;ballbounce.play();}
                    else if (ball[j].x>=xCheck4+67&&ball[j].x<=xCheck4+79) {ball[j].a=4;ball[j].b=-2;ballbounce.play();}
         Runnable pMovement = new Runnable()
             public void run()
                 while(moveB)
                     if(pauseB==false){
                     if (brick[0].y == 445) brick[0].y-=2; if (brick[0].y == 125) brick[0].y+=2;
                     if (brick[0].y<445&&brick[0].y>125){if (movecheck1==1){brick[0].y-=1;yCheck1 = brick[0].y;} 
                     else if (movecheck1==-1){brick[0].y+=1;yCheck1 = brick[0].y;} }
                     if (brick[1].y == 445) brick[1].y-=2; if (brick[1].y == 125) brick[1].y+=2;   
                     if (brick[1].y<445&&brick[1].y>125){if (movecheck2==1){brick[1].y-=1;yCheck2 = brick[1].y;}
                     else if (movecheck2==-1){brick[1].y+=1;yCheck2 = brick[1].y;}  }
                     if (brick[2].x == 445) brick[2].x-=2; if (brick[2].x == 125) brick[2].x+=2;   
                     if (brick[2].x<570&&brick[2].x>125){if (movecheck3==1){brick[2].x-=1;xCheck3 = brick[2].x;}
                     else if (movecheck3==-1){brick[2].x+=1;xCheck3 = brick[2].x;}  }
                     if (brick[3].x == 445) brick[3].x-=2; if (brick[3].x == 125) brick[3].x+=2;   
                     if (brick[3].x<570&&brick[3].x>0){if (movecheck4==1){brick[3].x-=1;xCheck4 = brick[3].x;}
                     else if (movecheck4==-1){brick[3].x+=1;xCheck4 = brick[3].x;}  }
                     starter();
                     try{Thread.sleep(2,500);}catch(InterruptedException e){}              
                if(pauseB){try{Thread.sleep(2,500);}catch(InterruptedException e){}}
        public void starter()
            if(starter==1)
                if(gameflag==2){p1Dead=false; p2Dead=false; p3Dead=false; p4Dead=false;}
                if(gameflag==3 || gameflag==4){p3Dead=true;p4Dead=true;}
                a1=0;b1=0;c1=0;d1=0;drawB=true;
                starttext = false;
                win=0;
                score1=10;score2=10;score3=10;score4=10;
                if(gameflag==3 || gameflag==4){score3=0;score4=0;}       
                own=1;
                prepare.play();
                try{Thread.sleep(5000);}catch(InterruptedException e){}
                time=1;
                try{Thread.sleep(1000);}catch(InterruptedException e){}
                time=2;
                try{Thread.sleep(1000);}catch(InterruptedException e){}
                time=3;
                try{Thread.sleep(1000);}catch(InterruptedException e){}
                if(gameflag==2)
                    ball[0].a=2;ball[0].b=0;
                    ball[1].a=0;ball[1].b=-2;
                if(gameflag==3 || gameflag==4)
                    ball[0].a=2;ball[0].b=0;
                    ball[1].a=-2;ball[1].b=0;
                ball[0].x = 325; ball[0].y = 325;ball[1].x = 325; ball[1].y = 325;
                pause=0;time=-5;starter=0;begin=1;
        public void run()
            while(thisB)
                if(pauseB==false)
                switch(gameflag)
                    case INIT_ACTIVE:
                        repaint();
                        gameflag = INTRO_ACTIVE;
                        try{Thread.sleep(10);}
                        catch(InterruptedException ex){break;}
                        break;
                    case INTRO_ACTIVE:             
                        physicsintro();
                        try{Thread.sleep(10);}
                        catch(InterruptedException ex){break;}
                        for(int w = 0;w<8;w++){ball2[w].x+=ball2[w].a;ball2[w].y+=ball2[w].b;}
                        repaint();
                        break;
                    case GAME1_ACTIVE:
                        if(countDead())resetter();
                        boundaries();
                        paddlephys();
                        for(int w = 0;w<2;w++){ball[w].x+=ball[w].a;ball[w].y+=ball[w].b;}                  
                        try{Thread.sleep(7,500);}catch(InterruptedException e){break;}     
                        repaint();  
                    case GAME2_ACTIVE:
                        if(countDead())resetter();
                        boundaries();
                        paddlephys();
                        for(int w = 0;w<2;w++){ball[w].x+=ball[w].a;ball[w].y+=ball[w].b;}                  
                        try{Thread.sleep(7,500);}catch(InterruptedException e){break;}     
                        repaint();  
                    case GAME3_ACTIVE:
                        if(countDead())resetter();
                        boundaries();
                        paddlephys();
                        for(int w = 0;w<2;w++){ball[w].x+=ball[w].a;ball[w].y+=ball[w].b;}                  
                        try{Thread.sleep(7,500);}catch(InterruptedException e){break;}     
                        repaint();  
                if(pauseB==true){repaint();try{Thread.sleep(7,500);}catch(InterruptedException e){}}
        public void boundaries()
            for(int z = 0; z<2;z++)
                ranB1 = (int)(Math.random() * 4);
                //P1 scores
                if(p1Dead==false && ball[z].y<525 && ball[z].y>125 && ball[z].x<2)
                    if(score1==1)humiliation.play();
                    else headshot.play();               
                    score1--;cons1++;              
                    ball[z].y=325;ball[z].x=325;
                    if(ranB1==0){ball[z].a=1;ball[z].b=1;}else if(ranB1==1){ball[z].a=-1;ball[z].b=1;}
                    else if(ranB1==2){ball[z].a=1;ball[z].b=-1;}else if(ranB1==3){ball[z].a=-1;ball[z].b=-1;}               
                    if(score1 == 0)p1Dead=true;                                                        
                //P2 scores
                else if(p2Dead==false&& ball[z].y<525 && ball[z].y>125 && ball[z].x>648)
                    if(score2==1)humiliation.play();
                    else headshot.play();
                    score2--;cons2++;     
                    ball[z].y = 325;ball[z].x=325;
                    if(ranB1==0){ball[z].a=1;ball[z].b=1;}else if(ranB1==1){ball[z].a=-1;ball[z].b=1;}
                    else if(ranB1==2){ball[z].a=1;ball[z].b=-1;}else if(ranB1==3){ball[z].a=-1;ball[z].b=-1;}
                    if(score2 == 0)p2Dead=true;
                //P3 scores
                else if(p3Dead==false&&ball[z].x<525 && ball[z].x>125 && ball[z].y<2)
                    if(score3==1)humiliation.play();
                    else headshot.play();               
                    score3--;cons3++;          
                    ball[z].y = 325; ball[z].x = 325;
                    if(ranB1==0){ball[z].a=1;ball[z].b=1;}else if(ranB1==1){ball[z].a=-1;ball[z].b=1;}
                    else if(ranB1==2){ball[z].a=1;ball[z].b=-1;}else if(ranB1==3){ball[z].a=-1;ball[z].b=-1;}
                    if(score3 == 0)p3Dead=true;
                //P4 Scores
                else if(p4Dead==false&&ball[z].x<525 && ball[z].x>125 && ball[z].y>648)
                    if(score4==1)humiliation.play();
                    else headshot.play();
                    score4--;cons4++;            
                    ball[z].y = 325; ball[z].x = 325;
                    if(ranB1==0){ball[z].a=1;ball[z].b=1;}else if(ranB1==1){ball[z].a=-1;ball[z].b=1;}
                    else if(ranB1==2){ball[z].a=1;ball[z].b=-1;}else if(ranB1==3){ball[z].a=-1;ball[z].b=-1;}
                    if(score4 == 0)p4Dead=true;
                if((p1Dead==true && ball[z].y<525 && ball[z].y>125 && ball[z].x<2) || (gameflag==3 || gameflag == 4))
                    ballbounce.play();ball[z].a*=-1;
                else if((p2Dead==true && ball[z].y<525 && ball[z].y>125 && ball[z].x>648) || (gameflag==3 || gameflag == 4))
                    ballbounce.play();ball[z].a*=-1;
                else if((p3Dead==true &&ball[z].x<525 && ball[z].x>125 && ball[z].y<2) || (gameflag==3 || gameflag == 4))
                    ballbounce.play();ball[z].b*=-1;
                else if((p4Dead==true &&ball[z].x<525 && ball[z].x>125 && ball[z].y>648) || (gameflag==3 || gameflag == 4))
                    ballbounce.play();ball[z].b*=-1;
                if(poly1.contains(ball[z].x,ball[z].y))
                    ballbounce.play();
                    if(ranB1 == 0){ball[z].a=1;ball[z].b=5;}else if(ranB1 == 1){ball[z].a=2;ball[z].b=4;}
                    else if(ranB1 == 2){ball[z].a=5;ball[z].b=1;}else if(ranB1 == 3){ball[z].a=4;ball[z].b=2;}
                else if(poly2.contains(ball[z].x,ball[z].y))
                    ballbounce.play();
                    if(ranB1 == 0){ball[z].a=1;ball[z].b=-5;}else if(ranB1 == 1){ball[z].a=2;ball[z].b=-4;}
                    else if(ranB1 == 2){ball[z].a=5;ball[z].b=-1;}else if(ranB1 == 3){ball[z].a=4;ball[z].b=-2;}
                else if(poly3.contains(ball[z].x,ball[z].y))
                    ballbounce.play();
                    if(ranB1 == 0){ball[z].a=-1;ball[z].b=5;}else if(ranB1 == 1){ball[z].a=-2;ball[z].b=4;}
                    else if(ranB1 == 2){ball[z].a=-5;ball[z].b=1;}else if(ranB1 == 3){ball[z].a=-4;ball[z].b=2;}
                else if(poly4.contains(ball[z].x,ball[z].y))
                    ballbounce.play();
                    if(ranB1 == 0){ball[z].a=-1;ball[z].b=-5;}else if(ranB1 == 1){ball[z].a=-2;ball[z].b=-4;}
                    else if(ranB1 == 2){ball[z].a=-5;ball[z].b=-1;}else if(ranB1 == 3){ball[z].a=-4;ball[z].b=-2;}
        public void resetter()
            brick[0].x=25;brick[0].y=285;brick[1].x=615;brick[1].y=285;brick[2].x=285;brick[2].y=25;brick[3].x=285;brick[3].y=615;
            if(p4Dead==true && p3Dead==true && p2Dead==true && p1Dead==false){ball[0].x = 325;ball[0].y = 325;ball[1].x = 325;ball[1].y = 325;
                ball[0].a=0;ball[0].b=0;ball[1].a=0;ball[1].b=0;drawB=false;match.play();pause=5;p1Dead=true;begin=0;win=1;winner=1;stringWin="Player 1 Wins";}
            else if(p4Dead==true && p3Dead==true && p2Dead==false && p1Dead==true){ball[0].x = 325;ball[0].y = 325;ball[1].x = 325;ball[1].y = 325;
                ball[0].a=0;ball[0].b=0;ball[1].a=0;ball[1].b=0;drawB=false;match.play();pause=5;p2Dead=true;begin=0;win=1;winner=2;stringWin="Player 2 Wins";}
            else if(p4Dead==true && p3Dead==false && p2Dead==true && p1Dead==true){ball[0].x = 325;ball[0].y = 325;ball[1].x = 325;ball[1].y = 325;
                ball[0].a=0;ball[0].b=0;ball[1].a=0;ball[1].b=0;drawB=false;match.play();pause=5;p3Dead=true;begin=0;win=1;winner=3;stringWin="Player 3 Wins";}
            else if(p4Dead==false && p3Dead==true && p2Dead==true && p1Dead==true){ball[0].x = 325;ball[0].y = 325;ball[1].x = 325;ball[1].y = 325;
                ball[0].a=0;ball[0].b=0;ball[1].a=0;ball[1].b=0;drawB=false;match.play();pause=5;p4Dead=true;begin=0;win=1;winner=4;stringWin="Player 4 Wins";}       
        public boolean countDead()
            if(gameflag==2)
                if(p4Dead==true)a1=1;if(p3Dead==true)b1=1;if(p2Dead==true)c1=1;if(p1Dead==true)d1=1;
                dead = a1 + b1 + c1 + d1;
                if(dead>2)return true;
                else return false;
            if(gameflag==3 || gameflag==4)
                if(p2Dead==true)c1=1;if(p1Dead==true)d1=1;
                dead = c1 + d1;
                if(dead==1) return true;
                else return false;
            return false;
        public void physicsintro()
            for(int aw = 0;aw<8;aw++)
                if(ball2[aw].x >645 || ball2[aw].x < 5)ball2[aw].a *= -1;
                if(ball2[aw].y > 720 || ball2[aw].y <5)ball2[aw].b *= -1;
        public void mouseExited(MouseEvent e){}
        public void mouseEntered(MouseEvent e){}
        public void mouseReleased(MouseEvent e){}
        public void mousePressed(MouseEvent e){}
        public void mouseClicked(MouseEvent e) 
                // resume
                if(pause==1 && e.getX()>=270 && e.getX()<= 360 && e.getY()>=650)
                    pauseB=false;pause=0;
                // pause
                else if(pause==0 && e.getX()>=270 && e.getX()<= 360 && e.getY()>=650)
                   pauseB=true;pause=1;             
                //start
                else if(begin == 0 && e.getX()>=270 && e.getX()<= 360 && e.getY()>=650)
                    starter = 1;              
        public void mouseMoved(MouseEvent e)
            //gui light up
            if(e.getX()>=270 && e.getX()<= 360 && e.getY()>=650){Color1 = new Color(255,255,255);}
            else{Color1 = new Color(0,0,0);}         
            repaint();
        public void mouseDragged(MouseEvent e){}
        public void keyTyped(KeyEvent e){}
        public void keyPressed(KeyEvent e)
            c = e.getKeyCode();
            if(gameflag==2 || gameflag==3)
            switch(c)
                case KeyEvent.VK_1:
                movecheck1 = 1;break;
                case KeyEvent.VK_2:
                movecheck1 = -1;break;           
                case KeyEvent.VK_V:
                movecheck2 = 1;break;
                case KeyEvent.VK_B:
                movecheck2 = -1;break;
                case KeyEvent.VK_K:
                movecheck3 = 1;break;
                case KeyEvent.VK_L:
                movecheck3 = -1;break;
                case KeyEvent.VK_LEFT:
                movecheck4 = 1;break;
                case KeyEvent.VK_DOWN:
                movecheck4 = -1;break;
            if(gameflag==1)
            switch(c)
                case KeyEvent.VK_UP:
                if(colorChange==0)colorChange=2;
                else if(colorChange==1)colorChange=0;
                else if(colorChange==2)colorChange=1;break;
                case KeyEvent.VK_DOWN:
                if(colorChange==0)colorChange=1;
                else if(colorChange==1)colorChange=2;
                else if(colorChange==2)colorChange=0;break;
                case KeyEvent.VK_ENTER:
                if(colorChange==0)gameflag=2;
                if(colorChange==1)gameflag=3;
                if(colorChange==2)gameflag=4;
                 break;
        public void keyReleased(KeyEvent e)
            c = e.getKeyCode();
            if (gameflag==2 || gameflag==3)
            switch(c)
                case KeyEvent.VK_1:
                movecheck1 = 0;break;
                case KeyEvent.VK_2:
                movecheck1 = 0;break;
                case KeyEvent.VK_V:
                movecheck2 = 0;break;
                case KeyEvent.VK_B:
                movecheck2 = 0;break;
                case KeyEvent.VK_K:
                movecheck3 = 0;break;
                case KeyEvent.VK_L:
                movecheck3 = 0;break;
                case KeyEvent.VK_LEFT:
                movecheck4 = 0;break;
                case KeyEvent.VK_DOWN:
                movecheck4 = 0;break;
    {co                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  

    Japplet is Swing. Your double buffering code is unneccessary. And you are painting wrong. You should be using paintComponent and not paint. And throw away the
    buffered image and update while you are at it.

  • Using 6533 DIO32HS, is it possible to use double buffered output with varying pauses?

    I'm using Level-Ack handshaking to transmit data. Currently, I'm hooked up to a loop-back on the DIO32HS card.
    If I don't use double-buffering, I end up with pauses in data transmission, so I need to use double buffering. Unfortunately, I can't seem to set up a delay in the middle of a double buffered scheme.
    What I need to do is this:
    Transmit 64 packets of data (16 bits each) on group 2 / Receive 64 packets of data (16 bits each) on group 1
    Delay for .2 ms
    Transmit the same packets again / receive
    The delay in the middle will need to be varied, from .2 to 20 ms.
    I'm programming in Visual C++ 6.0 under Windows 2000, with (as suggested above) group1 c
    onfigured as input (DIOA and DIOB) and group2 set up as output (DIOC and DIOD). Due to the speed of transmission (256kHz) and the small size of the data set, the program I wrote, no matter how tight I try to make it, cannot insert the proper delay and start the next send on time.
    Does anyone have any idea if such a pause is possible? Anyone know how to do it, or any suggestions on what to try?
    Thanks!

    .2 ms is a very small time delay to use in software. Windows usually isn't more accurate than about 10 or 20 ms. If you need to have small, precise delays you could either use a real time OS, like pharlap and LabVIEW RT, or use extra hardware to generate the delays correctly.
    I would recommend using a separate MIO or counter/timer board (like a 660x) to generate timing pulses for the DIO32HS. This gives you precise timing control at high speed. If the 32HS is in Level ACK Mode, it will respond to external ACK and REQ signals. This is covered in more detail on page 5-10 of the PCI-DIO32HS User Manual.

  • Double Buffering +MVC

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

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

  • Double buffering method - confusion

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

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

Maybe you are looking for

  • Full internet routing in an internet MPLS VPN

    Is it possible and advisable to run the full internet routing table in a seperate MPLS VRF. A default route is not an option With kind regards, Mike

  • Integration SCM (EWM) 7.01  to ERP ECC 6.0

    Hello, we are "trying" to integrate an SCM 7.0.1 to an ERP ECC 6.0. Material master data and goods received deliveries will be transfered from ERP to SCM sucessfull, but the quotation and the goods movement based on the purchase order  at ERP does no

  • TS1609 Error when installing or updating iTunes on Windows 8

    When I try to install or update iTunes, I receive a message to the effect that there has been a failure to install property. It is suggested that I verify that I have sufficient privileges to start system services??? I have full administrative privil

  • Very very slow import using LOG and Transfer

    I am using a CANON VIXAIA HF10.and the clips are importing very very slow. The max time on each clip is only 5 min or so. Is there a way to speed this up? Thanks.

  • Why i need to press the push button twice to complete my action?

    in my Push Button at WHEN-BUTTON-PRESSED trigger I wrote this code: =================================== FORMS_DDL('CREATE TABLE DEMO (DEMO_ID NUMBER ENCRYPT USING ''AES256'' NO SALT NULL, DEMO_DATE DATE ENCRYPT USING ''AES256'' NO SALT NOT NULL)'); F