どのように私は、Swingのマウスイベントが発生して監視するかを決定するのですか?
-
12-09-2019 - |
質問
私は、マウスの押下を検出するために、コンポーネント上でのJavaのMouseListenerを持っています。どのように私は、マウスのプレスがで発生した監視た伝えることができますか?
@Override
public void mousePressed(MouseEvent e) {
// I want to make something happen on the monitor the user clicked in
}
私が達成しようとしている効果がある:ユーザーが自分のアプリケーション内でマウスボタンを押したときにマウスが解放されるまで、ポップアップウィンドウは、いくつかの情報を示しています。私は、ユーザーがクリックした場合、このウィンドウが配置されていることを確認したいのですが、ウィンドウ全体が表示されるように、私は現在の画面上のウィンドウの位置を調整する必要があります。
解決
あなたは Javaから表示情報を取得することができます.awt.GraphicsEnvironmentする。あなたは、ローカルシステムに関する情報を取得するためにこれを使用することができます。各モニタの境界を含む。
Point point = event.getPoint();
GraphicsEnvironment e
= GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] devices = e.getScreenDevices();
Rectangle displayBounds = null;
//now get the configurations for each device
for (GraphicsDevice device: devices) {
GraphicsConfiguration[] configurations =
device.getConfigurations();
for (GraphicsConfiguration config: configurations) {
Rectangle gcBounds = config.getBounds();
if(gcBounds.contains(point)) {
displayBounds = gcBounds;
}
}
}
if(displayBounds == null) {
//not found, get the bounds for the default display
GraphicsDevice device = e.getDefaultScreenDevice();
displayBounds =device.getDefaultConfiguration().getBounds();
}
//do something with the bounds
...
他のヒント
リッチの答えは私が全体の解決策を見つける助けました
public void mousePressed(MouseEvent e) {
final Point p = e.getPoint();
SwingUtilities.convertPointToScreen(p, e.getComponent());
Rectangle bounds = getBoundsForPoint(p);
// now bounds contains the bounds for the monitor in which mouse pressed occurred
// ... do more stuff here
}
private static Rectangle getBoundsForPoint(Point point) {
for (GraphicsDevice device : GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()) {
for (GraphicsConfiguration config : device.getConfigurations()) {
final Rectangle gcBounds = config.getBounds();
if (gcBounds.contains(point)) {
return gcBounds;
}
}
}
// if point is outside all monitors, default to default monitor
return GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
}
Javaの1.6ので、あなたは、イベントを生成したコンポーネントの位置を取得する必要があり、以前のバージョンでは、でgetLocationOnScreenを使用することができます
Point loc;
// in Java 1.6
loc = e.getLocationOnScreen();
// in Java 1.5 or previous
loc = e.getComponent().getLocationOnScreen();
あなたは、画面の境界を取得するためのGraphicsEnvironmentクラスを使用する必要があります。
たぶんe.getLocationOnScreen();動作します?これは、Java 1.6のためだけです。
所属していません StackOverflow