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

前端 未结 4 915
攒了一身酷
攒了一身酷 2020-12-06 02:30

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 mousePres         


        
4条回答
  •  离开以前
    2020-12-06 03:09

    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
    ...
    

提交回复
热议问题