title: How do I get a Graphic2D object to follow a mouse pointer exactly in Java?
body: <p>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. </p>
  
  <p>Am I doing something wrong?  </p>
  
  <p>Why is there a distance between my mouse pointer and the Rectangle object?</p>
  
  <pre><code>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);          
      }
  }
  </code></pre>