简体   繁体   中英

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);          
    }
}
  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM