Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically clicking a GUI button in Java Swing

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.

like image 360
Gigatron Avatar asked Feb 24 '11 19:02

Gigatron


People also ask

What method is called when a user clicks a button on a Swing GUI?

The actionPerformed method is used when a button is clicked normally.


2 Answers

Have you tried using doClick()?

like image 117
JasCav Avatar answered Sep 21 '22 19:09

JasCav


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); } 
like image 30
Martijn Courteaux Avatar answered Sep 23 '22 19:09

Martijn Courteaux