Как определить, на каком мониторе происходит событие мыши Swing?
У меня есть Java MouseListener на компоненте для обнаружения мышь. Как я могу определить, на каком мониторе находился нажатие мыши?
@Override
public void mousePressed(MouseEvent e) {
// I want to make something happen on the monitor the user clicked in
}
Эффект, который я пытаюсь достичь, заключается в следующем: когда пользователь нажимает кнопку мыши в моем приложении, всплывающее окно показывает некоторую информацию, пока мышь не будет выпущена. Я хочу, чтобы это окно было расположено там, где пользователь нажимает, но мне нужно настроить положение окна на текущем экране, чтобы было видно все окно.
Ответы
Ответ 1
Вы можете получить отображаемую информацию из 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
...
Ответ 2
Богатый ответ помог мне найти целое решение:
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();
}
Ответ 3
Так как Java 1.6 вы можете использовать getLocationOnScreen, в предыдущих версиях вы должны получить местоположение компонента, сгенерировавшего событие:
Point loc;
// in Java 1.6
loc = e.getLocationOnScreen();
// in Java 1.5 or previous
loc = e.getComponent().getLocationOnScreen();
Вам понадобится использовать класс GraphicsEnvironment, чтобы получить границу экрана.
Ответ 4
Возможно, e.getLocationOnScreen(); будет работать? Это только для java 1.6.