Identifying Swing component at a particular screen coordinate? (And manually dispatching MouseEvents)

ぃ、小莉子 提交于 2019-12-04 00:12:53

问题


I'm doing some work making a Java app compatible with alternative input devices. Unfortunately, the device in question has a Java API that's barely into the alpha stages right now, so it's pretty poor. What I need to do is essentially set up a replacement structure for the dispatch of MouseEvents. Does anyone know if there's a way in Swing to take a screen coordinate and find out what Swing component is displayed on top at that screen point?


回答1:


In AWT Container, call this ...

findComponentAt(int x, int y) 
          Locates the visible child component that contains the specified position

i.e. If it is in a GlassPane...

  public static Component findComponentUnderGlassPaneAt(Point p, Component top) {
    Component c = null;

    if (top.isShowing()) {
      if (top instanceof RootPaneContainer)
        c =
        ((RootPaneContainer) top).getLayeredPane().findComponentAt(
            SwingUtilities.convertPoint(top, p, ((RootPaneContainer) top).getLayeredPane()));
      else
        c = ((Container) top).findComponentAt(p);
    }

    return c;
  }

Reading your question, this might be of help to you also...

If you want to exercise the control use this ... Java.awt.Robot class is used to take the control of mouse and keyboard. Once you get the control, you can do any type of operation related to mouse and keyboard through your java code. This class is used generally for test automation.




回答2:


An alternative (may require further tweaking):

public static Component findComponentUnderMouse() {
    Window window = findWindow();
    Point location = MouseInfo.getPointerInfo().getLocation();
    SwingUtilities.convertPointFromScreen(location, window);
    return SwingUtilities.getDeepestComponentAt(window, location.x, location.y);
}

private static Window findWindow() {
    for (Window window : Window.getWindows()) {
        if (window.getMousePosition(true) != null)
            return window;
    }

    return null;
}



回答3:


to take a component screen coordinates in Swing you may by method getLocationOnScreen()



来源:https://stackoverflow.com/questions/2733896/identifying-swing-component-at-a-particular-screen-coordinate-and-manually-dis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!