【问题标题】:Getting mouse position in a transparent window在透明窗口中获取鼠标位置
【发布时间】:2016-08-12 08:33:04
【问题描述】:

所以我有一个透明窗口,可以绘制几条线和 hud 元素。我想知道当我点击热键设置(例如 ctrl-s 或其他东西)并保存鼠标 x 和 y 时,是否有办法在所述窗口中获取鼠标的位置,以便我可以重新绘制框架更新后的变量。

我的框架代码是这样的:

JFrame frame = new JFrame();
frame.setUndecorated(true);
frame.add(new AimDriver());
frame.setBackground(new Color(0,0,0,0));
frame.setSize(resolutionX, resolutionY);
frame.setAlwaysOnTop(true);
frame.setVisible(true);

aimDriver 拥有所有的绘画方法。感谢您的帮助!

【问题讨论】:

标签: java swing jframe transparent key-events


【解决方案1】:

KeyBindingKeyListener 相比具有多项优势。也许最重要的优势是KeyBinding 不会受到困扰KeyListener 的焦点问题(有关详细说明,请参阅this question。)

以下方法遵循KeyBinding Java Tutorial。首先,创建一个AbstractAction,用于捕获鼠标在窗口中的位置:

AbstractAction action = new AbstractAction() {

    @Override
    public void actionPerformed(ActionEvent e) {
        Point mLoc = MouseInfo.getPointerInfo().getLocation();
        Rectangle bounds = frame.getBounds();

        // Test to make sure the mouse is inside the window
        if(bounds.contains(mLoc)){
            Point winLoc = bounds.getLocation();
            mouseLoc = new Point(mLoc.x - winLoc.x, mLoc.y - winLoc.y);
        }

    }
};

注意:测试窗口是否包含鼠标位置很重要;如果不这样做,鼠标位置很容易包含无意义的坐标(例如 (-20,199930),这意味着什么?)。

现在您已经有了所需的操作,创建适当的KeyBinding

// We add binding to the RootPane 
JRootPane rootPane = frame.getRootPane();

//Specify the KeyStroke and give the action a name
KeyStroke KEY = KeyStroke.getKeyStroke("control S");
String actionName = "captureMouseLoc";

//map the keystroke to the actionName
rootPane.getInputMap().put(KEY, actionName);

//map the actionName to the action itself
rootPane.getActionMap().put(actionName, action);

【讨论】:

    【解决方案2】:

    为你的框架对象添加一个键监听器。您可以使用this 帖子作为参考。转到上面帖子中的 keyPressed 事件并将 println 方法替换为代码以检索鼠标指针位置并更新您的位置变量。您应该能够使用此代码来获取 JFrame 中的相对鼠标坐标。

    int xCoord = MouseInfo.getPointerInfo().getLocation().x - frame.getLocationOnScreen().x;
    int yCoord = MouseInfo.getPointerInfo().getLocation().y - frame.getLocationOnScreen().y;
    

    【讨论】:

      猜你喜欢
      • 2018-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-01
      • 1970-01-01
      • 2011-08-07
      • 1970-01-01
      • 2013-01-20
      相关资源
      最近更新 更多