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

前端 未结 3 657
北恋
北恋 2021-01-11 15:01

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 r

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-11 15:33

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

提交回复
热议问题