如何在Java Swing的JFrame中设置光标位置?
Java Swing游戏光标控制解决方案
1. 强制限制光标在窗口范围内
不用退出程序,直接把光标锁定在JFrame内,彻底避免移出窗口的报错问题。通过MouseMotionListener监听鼠标移动,结合Robot类强制拉回超出边界的光标:
import java.awt.*; import java.awt.event.MouseMotionAdapter; import java.awt.event.MouseEvent; import javax.swing.JFrame; public class GameFrame extends JFrame { private Robot robot; public GameFrame() { setSize(800, 600); setDefaultCloseOperation(EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); try { robot = new Robot(); } catch (AWTException e) { e.printStackTrace(); } addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseMoved(MouseEvent e) { Rectangle winBounds = getBounds(); int screenCursorX = e.getXOnScreen(); int screenCursorY = e.getYOnScreen(); int newX = screenCursorX; int newY = screenCursorY; boolean needAdjust = false; // 左边界 if (screenCursorX < winBounds.x) { newX = winBounds.x + 5; needAdjust = true; } // 右边界 else if (screenCursorX > winBounds.x + winBounds.width - 10) { newX = winBounds.x + winBounds.width - 10; needAdjust = true; } // 上边界 if (screenCursorY < winBounds.y) { newY = winBounds.y + 5; needAdjust = true; } // 下边界 else if (screenCursorY > winBounds.y + winBounds.height - 10) { newY = winBounds.y + winBounds.height - 10; needAdjust = true; } if (needAdjust) { robot.mouseMove(newX, newY); } } }); } public static void main(String[] args) { new GameFrame(); } }
2. 主动设置光标到指定位置
如果需要主动将光标移到某个位置(比如窗口中心、敌人位置),直接用Robot.mouseMove(int screenX, int screenY)方法,参数是屏幕绝对坐标:
// 示例:将光标移到窗口中心 Rectangle winBounds = getBounds(); int centerScreenX = winBounds.x + winBounds.width / 2; int centerScreenY = winBounds.y + winBounds.height / 2; robot.mouseMove(centerScreenX, centerScreenY);
3. 修复移出窗口报错的根源
你遇到的报错,本质是敌人追踪逻辑未处理光标在窗口外的情况。可以在获取光标位置后先做边界校验,用窗口边缘值替代超出的坐标:
// 获取当前光标屏幕坐标 Point cursorPos = MouseInfo.getPointerInfo().getLocation(); Rectangle winBounds = getBounds(); // 校验并修正光标位置 if (!winBounds.contains(cursorPos)) { cursorPos.x = Math.max(winBounds.x, Math.min(cursorPos.x, winBounds.x + winBounds.width)); cursorPos.y = Math.max(winBounds.y, Math.min(cursorPos.y, winBounds.y + winBounds.height)); } // 用修正后的坐标计算敌人追踪路径 // enemy.moveTowards(cursorPos);
内容的提问来源于stack exchange,提问作者Alán Dryaev
相关产品推荐
相关产品推荐

