2016-04-19 21 views
-2

私はいくつかの線とハド要素を描画する透明なウィンドウを持っています。私はCtrlキーを押しながら何かのようなホットキーを打つと、ウィンドウ内でマウスの位置を取得する方法があるのだろうかと疑問に思っています。更新された変数。透明なウィンドウでマウスの位置を取得する

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)); 'A **完全に**透明なウィンドウは通常イベントを受け取りません。もっと早く助けを求めるには、[MCVE]または[短く、自己完結型の正しい例](http://www.sscce.org/)を投稿してください。 –

答えて

3

A KeyBindingKeyListener上にいくつかの利点を提供します。おそらく最も重要な利点は、KeyBindingは、以下のアプローチがKeyBinding Java Tutorialを次のKeyListener(詳細な説明のためのthis questionを参照してください。)

を苦しめることができ、焦点の問題に悩まされないということです。まず、ウィンドウ内でマウスの位置をキャプチャ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

フレームリスナーにキーリスナーを追加します。あなたは参考としてthisの投稿を使用することができます。上記の投稿からkeyPressedイベントに移動し、printlnメソッドをコードに置き換えてマウスポインタの位置を取得し、位置変数を更新します。このコードを使用して、JFrame内の相対的なマウス座標を取得できるはずです。

int xCoord = MouseInfo.getPointerInfo().getLocation().x - frame.getLocationOnScreen().x; 
int yCoord = MouseInfo.getPointerInfo().getLocation().y - frame.getLocationOnScreen().y; 
関連する問題