2010-04-28 31 views
10

我正在做一些工作,使Java應用程序與其他輸入設備兼容。不幸的是,有問題的設備有一個Java API,它現在幾乎不在alpha階段,所以它很差。我需要做的是基本上爲MouseEvent的派發建立一個替換結構。有誰知道在Swing中是否有方法獲取屏幕座標,並找出在該屏幕點上顯示的Swing組件?識別特定屏幕座標處的Swing組件? (並手動調度MouseEvents)

回答

15

在AWT容器,稱此...

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

即如果它是在玻璃面板...

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

閱讀你的問題,這可能會幫上你也。 ..

如果你想鍛鍊控制使用這個... Java.awt.Robot類是用來控制鼠標和鍵盤。一旦你掌握了控制權,你就可以通過你的java代碼進行與鼠標和鍵盤相關的任何類型的操作。這個類通常用於測試自動化。

+0

謝謝!我認爲必須有一些API調用,我只是在祖先樹上看起來不夠。關於機器人課的聽力是一個巨大的獎金;我不知道這樣的事情是否存在,而且你很有可能爲我節省了幾天的工作時間! – DVA 2010-04-29 02:08:04

+0

@DVA感謝您的評論,良好的反饋和熱心是讓人們回答問題的原因。樂意效勞 :) – 2010-04-29 11:20:07

3

另一種(可能需要進一步的調整):

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