javarefreshdrawbufferedimagemouse-listeners

Refresh BufferedImage


I wanted to create a simple paint brush in JFrame. To do it, I have created an BufferedImage and when the mouse is dragged, I've just redrawn it with set to the image changes.

The problem is that if I drag mouse too fast not all points are drawn. It looks like dotted line.

And here is my code where I update the image:

public void mouseDragged(MouseEvent evt) 
{   
    int x = evt.getX();
    int y = evt.getY();

    if(eraser == false)   
        this.Dice(x, y);
    else
        this.Eraser(x, y);

    g = (Graphics2D) this.getGraphics();
    g.drawImage(image, positionX, positionY, null);
    g.dispose();
}

In Dice and Eraser methods I make changes to the image (I set pixels). I don't really know how to repair it.

Thanks for your help.


Solution

  • I think this is due to Swing "buffering" the mouseDragged-event (i.e. if the mouse is moved more than one pixel per interrupt, it will only get called once). You could try storing the latest reported mouse position, and instead of calling this.Dice()/this.Eraser() once for the pixel, call it for everything in between the starting(last) position, and the position of the current mouse event.