我正在尝试阻止鼠标光标移动(保持光标在应用程序中心的位置),并且仍然能够处理mouseMoved
事件以便在太空中旋转相机。我尝试使用java.awt.Robot.mouseMove(int x, int y)
执行此操作,但它调用mouseMoved
事件我正在使用旋转相机,因此相机返回到之前的位置。
答案 0 :(得分:2)
如果您只是忽略Robot调用的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?)并绘制自己的光标。