2

I'm trying to prevent mouse cursor movement (keep cursor's position at application center) and still be able to handle mouseMoved event in order to rotate a camera in space. I tried to do this with java.awt.Robot.mouseMove(int x, int y) but it calls mouseMoved event that I'm using to rotate camera, so camera returns to previous position.

Bobulous
  • 12,967
  • 4
  • 37
  • 68
Dimansel
  • 401
  • 1
  • 5
  • 11
  • You can just make two if statements: `if (mouseX > centerX)` and `else if (x < centerX)`, right?. This would prevent the method to do anything if the mouse position was reset by a robot to centerX... (Of course the same with `y` if you want to actions after the mouse moved up or down.) – Lukas Rotter Aug 22 '15 at 19:26

1 Answers1

3

And if you just ignore mouseMoved-Events called by Robot?

You could save the position, the Robot moved the mouse. If you get a Mouse-Event with exactly these mouse-coordinates, just ignore this event. For me something like this worked:

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

import javax.swing.JFrame;

public class Test {
    // position, where mouse should stay
    private static final int fixX = 500;
    private static final int fixY = 500;

    private static Robot robo;
    private static JFrame frame;

    public static void main(String[] args) {
        // create robot
        try {
            robo = new Robot();
        } catch (AWTException e) {
            e.printStackTrace();
        }

        // create default frame with mouse listener
        frame = new JFrame("test frame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.addMouseMotionListener(new MouseMotionListener() {
            @Override
            public void mouseDragged(MouseEvent arg0) {
                move(arg0);
            }

            @Override
            public void mouseMoved(MouseEvent arg0) {
                move(arg0);
            }
        });
        frame.setSize(1000, 1000);
        frame.setVisible(true);
    }

    private static void move(MouseEvent arg0) {
        // check, if action was thrown by robot
        if (arg0.getX() == fixX && arg0.getY() == fixY) {
            // ignore mouse action
            return;
        }
        // move mouse to center (important: position relative to frame!)
        robo.mouseMove(fixX + frame.getX(), fixY + frame.getY());

        // compute and print move position
        int moveX = arg0.getX() - fixX;
        int moveY = arg0.getY() - fixY;
        System.out.println("moved: " + moveX + " " + moveY);
    }
}

The mouse stays at 500/500, you get your mouse movement, but you sometimes see the mouse jumping, because Robot is not fast enough.

Maybe you could just hide the System-Cursor (How to hide cursor in a Swing application?) and draw your own cursor.

Community
  • 1
  • 1
AnnoSiedler
  • 273
  • 1
  • 6