Programmatically clicking a GUI button in Java Swing

前端 未结 6 916
灰色年华
灰色年华 2020-12-13 23:06

How would I programmatically click a Swing JButton in a way that would register all the relevant action/mouse events and be visible to the user (i.e. they\'d see the button

6条回答
  •  春和景丽
    2020-12-13 23:51

    If doClick() is not what you want, you can move the mouse really to the button and press it:

    public void click(AbstractButton button, int millis) throws AWTException
    {
        Point p = button.getLocationOnScreen();
        Robot r = new Robot();
        r.mouseMove(p.x + button.getWidth() / 2, p.y + button.getHeight() / 2);
        r.mousePress(InputEvent.BUTTON1_MASK);
        try { Thread.sleep(millis); } catch (Exception e) {}
        r.mouseRelease(InputEvent.BUTTON1_MASK);
    }
    

提交回复
热议问题