识别特定屏幕坐标处的Swing组件?(并手动调度MouseEvents)

DVA*_*DVA 11 java swing mouseevent

我正在做一些工作使Java应用程序与其他输入设备兼容.不幸的是,这个设备有一个Java API,它现在几乎没有进入alpha阶段,所以它非常糟糕.我需要做的是基本上为MouseEvents的发送设置一个替换结构.有没有人知道Swing是否有办法获取屏幕坐标并找出在该屏幕点顶部显示的Swing组件?

Rom*_*eau 15

在AWT容器中,调用此...

findComponentAt(int x, int y) 
          Locates the visible child component that contains the specified position
Run Code Online (Sandbox Code Playgroud)

即如果它在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;
  }
Run Code Online (Sandbox Code Playgroud)

读你的问题,这对你也有帮助......

如果你想锻炼控件使用这个... Java.awt.Robot类用于控制鼠标和键盘.获得控件后,您可以通过java代码执行与鼠标和键盘相关的任何类型的操作.该类通常用于测试自动化.


Bra*_*ace 5

另一种选择(可能需要进一步调整):

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;
}
Run Code Online (Sandbox Code Playgroud)