2016-04-19 60 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;