문제

마우스 누르기를 감지하는 구성 요소에 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
...

다른 팁

Rich의 답변은 전체 해결책을 찾는 데 도움이되었습니다.

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