Java 在透明窗口中获取鼠标位置

Java 在透明窗口中获取鼠标位置,java,swing,jframe,transparent,key-events,Java,Swing,Jframe,Transparent,Key Events,所以我有一个透明的窗口,可以画一些线和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(resol

所以我有一个透明的窗口,可以画一些线和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拥有所有的绘画方法。谢谢你的帮助

将关键点侦听器添加到帧对象。您可以使用post作为参考。从上面的帖子转到keyPressed事件,用代码替换println方法,以检索鼠标指针位置并更新位置变量。您应该能够使用此代码获得JFrame中的相对鼠标坐标

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

KeyBinding
keylister
提供了一些优势。也许最重要的优点是,
KeyBinding
不会出现会困扰
keysister
的焦点问题(请参阅以获取详细解释)

以下方法遵循以下步骤。首先,创建一个
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);
        }

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

现在您已经完成了所需的操作,创建相应的
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);

当您的窗口/gui没有系统焦点时,您是否询问如何响应热键?
frame.setBackground(新颜色(0,0,0,0))完全透明的窗口通常不会接收事件。为了更快地获得更好的帮助,请发布一个or。