Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Freeze Mouse

Tags:

java

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!

like image 746
Ood Avatar asked Aug 13 '26 22:08

Ood


1 Answers

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.

like image 183
user1803551 Avatar answered Aug 16 '26 12:08

user1803551



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!