Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a Graphic2D object to follow a mouse pointer exactly in Java?

In the code below I have simply used a mouse listener to get the XY coordinates of the the mouse, and then call for a repaint. Within the paint method I've drawn a rectangle using the same XY coordinates for position. The rectangle does follow but at a distance from the mouse pointer. I'd expect the top left corner of the rectangle to touch the mouse pointer.

Am I doing something wrong?

Why is there a distance between my mouse pointer and the Rectangle object?

public void mouseMoved(MouseEvent e){
    x = e.getX();
    y = e.getY();

    repaint();
}

public class Canvas extends JPanel{
    Canvas(){}

    public void paint(Graphics g){
        Graphics2D g2 = (Graphics2D)g;
        g2.setPaint(Color.red);
        g2.fillRect(x, y, 50, 50);          
    }
}
like image 727
Gary Ryan Avatar asked Dec 22 '25 00:12

Gary Ryan


1 Answers

  1. Don't call your class Canvas, there is an AWT component by that name so it becomes confusing.

  2. Custom painting is done by overriding the paintComponent() method of the JPanel, not the paint() method.

  3. You don't show where you add the MouseListener to the panel. You are probably adding it to the frame instead.

If you need more help then post your SSCCE that demonstrates the problem.

like image 83
camickr Avatar answered Dec 23 '25 13:12

camickr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!