Image

Imagesparkymark wrote in Imagejava_dev

Perplexed: Freezing the mouse pointer

I have some code that successfully freezes the mouse pointer in one place during a drag operation by moving it back to the place it started after every mouseDragged event: I understand why doing that, with the Robot class, would itself provoke a mouseDragged event (the mouse pointer has moved, while the button was down) , but even if I try to handle that and I still find that net *attempted* motion of the mouse pointer (which is what I am trying to measure) is always zero due to mysterious mouseDragged events undoing the pixels that were (attempted to be) covered.

Suggestions welcome: the target application will use an invisible cursor during this drag: I don't want to just have an invisible cursor, for then if the mouse pointer is moved to the edge of the screen it will stop moving and I won't receive any new drag events, so I need to silently keep the mouse somewhere on the component, and then ultimately make the cursor visible in its original position in the mouseReleased method).

Edit: I think it was just a stupid, if subtle, bit of of bad arithmetic, described in the comments: a bit more obvious when the code is boiled down to the minimal reproducer behind the cut...


class ListenerAdditions extends MouseAdapter implements MouseMotionListener
 {
   private int x;// X-position of mousedown or any previous drag
   private int y; // Y-position

    Robot robot;
   {
    try
   {
      robot = new Robot();
   } catch (AWTException e)
   {
   }
   }
   PointerInfo info;
   private boolean midOperation=false;
  
   public void mousePressed(MouseEvent e)
   {
      x=e.getX();
      y=e.getY();
      info=MouseInfo.getPointerInfo();
      midOperation=false;
   }
   
   public void mouseDragged(MouseEvent e)
   {
         if (midOperation)
         { 
            System.out.println("That was the Robot?");
            midOperation = false;
            return;
         }
         
         int newX=e.getX();
         int newY=e.getY();
         
         System.out.println("dx="+(newX-x) +" dy="+(y-newY) ); // Counting up and to the right as positive
         x=newX;
         y=newY;
         midOperation = true;
         robot.mouseMove((int)info.getLocation().getX(), (int)info.getLocation().getY());
   }
}