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

前端 未结 4 923
攒了一身酷
攒了一身酷 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 02:50

    Rich's answer helped me find a whole solution:

    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();
    }
    

提交回复
热议问题