Search code examples
javaswingawtpaint

How to fill ellipses smoothly while dragging mouse


I'm using MouseMotion Listeners to add shapes to a HashSet, and then filling them in using Graphics2D. However when I move my mouse too fast the points no longer make a coherent line.

I've tried googling, but haven't found a relevant answer.

addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseDragged(MouseEvent e) {
                //points.add(new Point(e.getX(), e.getY()));
                shapes.add(new ShapeInfo(circle, new Point(e.getX(), e.getY()), color));
                repaint();
            }
        });
for(ShapeInfo info : shapes) {
            Point location = info.point.getLocation();
            g2d.translate(location.x, location.y);
            g2d.setColor(info.color);
            g2d.fill(info.shape);
            g2d.translate(-location.x, -location.y);
        }

I hope to get a nice, smooth line made of circles, but end up with sacttered circles. https://i.sstatic.net/ZfBl2.jpg <- Here is what happends when I drag the mouse too fast while painting.


Solution

  • Your mouse works at a certain frequency (normal mouse works around 100Hz) so it will pick a certain number of points while you move it.

    If you cover 1000 px in half second (which is not really fast) it will pick 50 points, they will be spaced every 20 pixel.

    If your circle has a radius of less than that you will see a dotted line.

    Even using very a fast mouse could not lead you to have a continuous line.

    You could draw a line between points instead of drawing a circle if you want, or interpolate coordinate between last circle and current one and create other circles in between the 2.