Search code examples
javaswingmouseeventmultiple-monitors

How do I determine which monitor a Swing mouse event occurs in?


I have a Java MouseListener on a component to detect mouse presses. How can I tell which monitor the mouse press occurred in?

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

The effect I'm trying to achieve is: when the user presses the mouse button in my app, a popup window shows some info, until the mouse is released. I want to ensure this window is positioned where the user clicks, but I need to adjust the window position on the current screen so that the entire window is visible.


Solution

  • You can get display information from java.awt.GraphicsEnvironment. You can use this to get a information about your local system. Including the bounds of each 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
    ...