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 being pressed as if they actually clicked it)?
The button is in the same application I'm running; I'm not trying to control a button in another application. I suppose I could directly inject events into the queue, but I'd prefer to avoid that approach if possible, and doing it that way wouldn't show a visible click.
I see the java.awt.Robot class offers methods to move the mouse and click the mouse, but not to make it click a particular button.
The actionPerformed method is used when a button is clicked normally.
Have you tried using doClick()?
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With