Alosyius
Alosyius

Reputation: 9151

Programmatically invoke click on JLabel

I have a event to listen for mouseclicks on my JLabel like:

private void jLabel4MouseClicked(java.awt.event.MouseEvent evt) { 

...

}

Is it possible to somehow invoke this programmatically?

And no I do not wish to use a button with doClick() :)

Upvotes: 0

Views: 1397

Answers (2)

juan.facorro
juan.facorro

Reputation: 9930

If you don't need any properties from the MouseEvent object then you could just call it with the null value. I would suggest though that if you have code that needs to be executed regardless of the click of the button, create a method with the corresponding parameters, call that method from the click handler and then from the other place where you need to call it.

private void jLabel4MouseClicked(java.awt.event.MouseEvent evt) { 
    this.Method(evt.getX(), evt.getY());
}

private void Method(int x, int y) {
  /// bla
}

Upvotes: 3

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285450

The Robot can be made to click anywhere, so yes it's possible. Check the Robot API and in particular the mouseMove(...), mousePress(...) and mouseRelease(...).

You would need to get the JLabel's screen coordinates first, but this is easily done via its getLocationOnScreen() and its getSize() method.

I'm curious as to your motivation for this.

Upvotes: 1

Related Questions