Как определить, на каком мониторе происходит событие мыши Swing?

StackOverflow https://stackoverflow.com/questions/1248386

Вопрос

У меня есть 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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top