A KeyBinding
KeyListener
上にいくつかの利点を提供します。おそらく最も重要な利点は、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);
ウィンドウ/ GUIにシステムのフォーカスがないときにホットキーに応答する方法を尋ねていますか? –
[キーバインディングの使用方法](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) – MadProgrammer
'frame.setBackground(new Color(0,0,0,0)); 'A **完全に**透明なウィンドウは通常イベントを受け取りません。もっと早く助けを求めるには、[MCVE]または[短く、自己完結型の正しい例](http://www.sscce.org/)を投稿してください。 –