Come faccio a determinare quale monitor un evento di oscillazione del mouse si verifica in?
-
12-09-2019 - |
Domanda
Ho un MouseListener Java su un componente per rilevare presse mouse. Come faccio a sapere che controllano la stampa del mouse si è verificato in?
@Override
public void mousePressed(MouseEvent e) {
// I want to make something happen on the monitor the user clicked in
}
L'effetto che sto cercando di realizzare è: quando l'utente preme il pulsante del mouse nella mia app, una finestra pop-up mostra alcune informazioni, fino a quando il mouse viene rilasciato. Voglio assicurare questa finestra è posizionato in cui l'utente fa clic, ma ho bisogno di regolare la posizione della finestra sullo schermo corrente in modo che l'intera finestra è visibile.
Soluzione
È possibile ottenere informazioni sul display da java .awt.GraphicsEnvironment . È possibile utilizzare questo per ottenere informazioni sul sistema locale. Compresi i limiti di ogni monitor.
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
...
Altri suggerimenti
di Rich mi ha aiutato a trovare una intera soluzione:
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();
}
Dal momento che Java 1.6 è possibile utilizzare getLocationOnScreen, nelle versioni precedenti è necessario ottenere la posizione del componente che ha generato l'evento:
Point loc;
// in Java 1.6
loc = e.getLocationOnScreen();
// in Java 1.5 or previous
loc = e.getComponent().getLocationOnScreen();
Si dovrà utilizzare la classe GraphicsEnvironment per ottenere il limite dello schermo.
Forse e.getLocationOnScreen (); funzionerà? E 'solo per Java 1.6.