Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to double buffer when drawing on a panel?

843806Aug 8 2008 — edited Aug 8 2008
Hi,

i'm drawing on a jpanel but when i move my mouse too fast the drawing won't draw a straight line, but instead a small gap appears between the two lines, i think because this is because the repaint() method is too slow to handle the speed of the mouse but i could be wrong. I thought about buffering but I read that buffering is done automatically with swing components like jpanel etc.

This demo i found on the net demonstrates my problem exactly (i didn't write it, but my application is too big to post the entire source here)
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class MouseMotionEventDemo extends JPanel implements MouseMotionListener {
  private int mX, mY;

  public MouseMotionEventDemo() {
    addMouseMotionListener(this);
    setVisible(true);
  }

  public void mouseMoved(MouseEvent me) {
    mX = (int) me.getPoint().getX();
    mY = (int) me.getPoint().getY();
    repaint();
  }

  public void mouseDragged(MouseEvent me) {
    mouseMoved(me);
  }

  public void paint(Graphics g) {
    g.setColor(Color.blue);
    g.fillRect(mX, mY, 5, 5);
  }

  public static void main(String[] args) {
    JFrame f = new JFrame();
    f.getContentPane().add(new MouseMotionEventDemo());
    f.setSize(200, 200);
    f.show();
  }

}

           
       
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Sep 5 2008
Added on Aug 8 2008
12 comments
74 views