Java – how do I determine which monitor the swing mouse event occurs on?

I have a Java mouselistener on the component to detect mouse press How do I know which monitor to press with the mouse?

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

What I'm trying to achieve is that when the user presses the mouse button in my application, the pop-up window will display some information until the mouse is released I want to make sure this window is where the user clicks, but I need to adjust the window position on the current screen so that the whole window is visible

Solution

You can start from Java awt. Get display information from graphicsenvironment You can use it to get information about the local system Include limits for 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
...
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>