I am trying to build an application similar to MS Paint. The problem I am having however is that when the mouse is dragged, the mouseDragged method call of MouseMotionListener interface is too slow. To just explain the problem using a simple application, I wrote this class.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class Temp extends JFrame
{
BufferedImage image = new BufferedImage (500,500, BufferedImage.TYPE_INT_RGB);
MyPanel panel = new MyPanel ();
Graphics g;
public Temp ()
{
g = image.getGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, 500, 500); // Clear the whole image
g.setColor(Color.black);
addWindowListener (new WindowAdapter ()
{
public void windowClosing (WindowEvent e)
{
System.exit (0);
}
}
);
panel.addMouseListener( new MouseAdapter ()
{
public void mousePressed (MouseEvent e)
{
g.fillOval(e.getX()-3, e.getY()-3 , 6, 6);
repaint ();
}
}
);
panel.addMouseMotionListener(new MouseMotionAdapter ()
{
public void mouseDragged (MouseEvent e)
{
g.fillOval(e.getX()-3, e.getY()-3 , 6, 6);
repaint ();
}
}
);
setSize (520,520);
getContentPane ().add(panel);
setVisible (true);
}
private class MyPanel extends JPanel
{
public void paintComponent (Graphics g)
{
super.paintComponent (g);
g.drawImage (image, 0, 0, null);
}
}
public static void main (String args [])
{
new Temp ();
}
}
If you perhaps run the program, and drag your mouse across the JFrame really fast, you'll notice that the drawing of circles is not too smooth and consistent. There is a big gap between the circles that are drawn. In contrast, if you do the same on MS Paint, the drawing is very smooth and consistent. No gaps between any of the drawn circles.
To further explain this problem, I am using the following image:
http://img210.imageshack.us/my.php?image=mousemotionyb4.jpg
As you can see in the image, the dots drawn are way apart from each other, unlike in the following image done in MS Paint.
http://img210.imageshack.us/my.php?image=mousemotion2ok3.jpg
Here they are in a nice consistent and smooth pattern.
Any idea how to correct this?
Edited by: Cricket_struck on Jan 29, 2009 8:03 PM
Edited by: Cricket_struck on Jan 29, 2009 8:05 PM