Dimansel
Dimansel

Reputation: 451

How to grab a mouse in Java Swing?

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.

Upvotes: 2

Views: 1117

Answers (1)

AnnoSiedler
AnnoSiedler

Reputation: 273

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.

Upvotes: 3

Related Questions