Ood
Ood

Reputation: 1805

Java - Freeze Mouse

Is there a way to lock the mouse in one position in Java for a certain amount of time?

I've tried this:

while(timer == true){

    Robot bot = new Robot();
    bot.mouseMove(x, y);

}

But when the user moves the mouse it jumps unpleasantly back and forth (from the position the user is dragging to the position where it's supposed to be locked).

Any ideas if there is a better way to do this? Or can I completely disable user input for the mouse? Thanks in advance!

Upvotes: 3

Views: 3582

Answers (1)

user1803551
user1803551

Reputation: 13427

This is as far as you can go (at least with the standard libraries). The mouse "jumps" are system dependent, specifically on the "sampling rate" of the listener. I'm not aware of a JVM parameter affecting it, but wouldn't be surprised if there is something in that spirit. The jumps are in opposite relation to the mouse acceleration (the mouse can move a "long" distance between the samples).

public class Stop extends JFrame {

    static Robot robot = null;
    static Rectangle bounds = new Rectangle(300, 300, 300, 300);
    static int lastX = 450; static int lastY = 450;

    Stop() {

        try {
            robot = new Robot();
        } catch (AWTException e) {
            e.printStackTrace();
        }
        addMouseMotionListener(new MouseStop());

        getContentPane().add(new JLabel("<html>A sticky situation<br>Hold SHIFT to get out of it", JLabel.CENTER));
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setBounds(bounds);
        setVisible(true);
    }

    private static class MouseStop extends MouseAdapter {

        @Override
        public void mouseMoved(MouseEvent e) {

            if(e.isShiftDown()) {
                lastX = e.getXOnScreen();
                lastY = e.getYOnScreen();
            }
            else
                robot.mouseMove(lastX, lastY);
        }
    }

    public static void main(String args[]) {

        new Stop();
    }
}

Edit: I have just gotten an idea involving painting of the cursor to appear as if the mouse is not moving at all. I'll add code if I get something working.

Upvotes: 4

Related Questions