如何在 Java Swing 中抓取鼠标?

How to grab a mouse in Java Swing?

我试图阻止鼠标光标移动(将光标的位置保持在应用程序中心)并且仍然能够处理 mouseMoved 事件以便在 space 中旋转相机。我尝试用 java.awt.Robot.mouseMove(int x, int y) 来做到这一点,但它调用了我用来旋转相机的 mouseMoved 事件,所以相机 returns 到以前的位置。

如果你只是忽略机器人调用的mouseMoved-Events?

您可以保存位置,机器人移动了鼠标。如果您得到的鼠标事件恰好包含这些鼠标坐标,请忽略此事件。对我来说,这样的事情有效:

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);
    }
}

鼠标保持在500/500,你可以看到你的鼠标移动,但有时你会看到鼠标跳动,因为机器人不够快。

也许您可以隐藏系统光标 (How to hide cursor in a Swing application?) 并绘制您自己的光标。