Programmatically clicking a GUI button in Java Swing

Gigatron picture Gigatron · Feb 24, 2011 · Viewed 90.1k times · Source

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.

Answer

JasCav picture JasCav · Feb 24, 2011

Have you tried using doClick()?