代码之家  ›  专栏  ›  技术社区  ›  Steve McLeod

如何确定在哪个监视器中发生了摆动鼠标事件?

  •  10
  • Steve McLeod  · 技术社区  · 16 年前

    我在一个组件上有一个JavaMouististor来检测鼠标按下。我怎样才能知道鼠标按下发生在哪个监视器中?

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

    我试图达到的效果是:当用户在我的应用程序中按下鼠标按钮时,一个弹出窗口会显示一些信息,直到鼠标被释放。我想确保此窗口位于用户单击的位置,但我需要调整当前屏幕上的窗口位置,以使整个窗口可见。

    4 回复  |  直到 8 年前
        1
  •  13
  •   Victor Grazi    8 年前

    您可以从 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
    ...
    
        2
  •  2
  •   Steve McLeod    16 年前

    里奇的回答帮助我找到了一个完整的解决方案:

    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();
    }
    
        3
  •  1
  •   oscargm    16 年前

    由于Java 1.6可以使用GETLooCuffon屏幕,在以前的版本中,必须获得生成事件的组件的位置:

    Point loc;
    // in Java 1.6
    loc = e.getLocationOnScreen();
    // in Java 1.5 or previous
    loc = e.getComponent().getLocationOnScreen();
    

    您必须使用graphicsEnvironment类来获取屏幕的绑定。

        4
  •  0
  •   Denis Tulskiy    16 年前

    也许E.GetLocationOnScreen();会工作吗?它只适用于Java 1.6。