Как определить, на каком мониторе происходит событие мыши Swing? - PullRequest
10 голосов
/ 08 августа 2009

У меня есть Java MouseListener на компоненте для обнаружения нажатий мыши. Как узнать, на каком мониторе произошло нажатие мыши?

@Override
public void mousePressed(MouseEvent e) {
  // I want to make something happen on the monitor the user clicked in
}

Эффект, которого я пытаюсь добиться, заключается в следующем: когда пользователь нажимает кнопку мыши в моем приложении, во всплывающем окне отображается некоторая информация, пока мышь не будет отпущена. Я хочу убедиться, что это окно расположено там, где пользователь щелкает, но мне нужно отрегулировать положение окна на текущем экране, чтобы было видно все окно.

Ответы [ 4 ]

13 голосов
/ 08 августа 2009

Информацию об отображении можно получить из 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 голосов
/ 08 августа 2009

Ответ Рича помог мне найти полное решение:

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();
}
1 голос
/ 08 августа 2009

Начиная с Java 1.6 вы можете использовать getLocationOnScreen, в предыдущих версиях вы должны получить местоположение компонента, который сгенерировал событие:

Point loc;
// in Java 1.6
loc = e.getLocationOnScreen();
// in Java 1.5 or previous
loc = e.getComponent().getLocationOnScreen();

Вам придется использовать класс GraphicsEnvironment, чтобы получить границы экрана.

0 голосов
/ 08 августа 2009

Может быть, e.getLocationOnScreen (); буду работать? Это только для Java 1.6.

...