2016-04-19 61 views
-2

所以我有一个透明的窗口绘制几行和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拥有所有的绘画方法。谢谢你的帮助!

+1

您是否在问窗口/ gui没有系统焦点时如何响应热键? –

+1

[如何使用键绑定](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) – MadProgrammer

+1

'frame.setBackground(new Color(0,0,0,0));一个完全**透明的窗口通常不会接收事件。为了尽快提供更好的帮助,请发布[MCVE]或[简短,独立,正确的示例](http://www.sscce.org/)。 –

回答

3

KeyBinding通过一个KeyListener提供了几个优点。也许最重要的优势是,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); 
0

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

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