I'm in need of simulating a MouseEvent.MOUSE_CLICKED
. I want to use the fireEvent method of a particular Node in order to dispatch an event of the aforementioned type. However, I am struggling with generating one. It appears that javafx.scene.input.MouseEvent has no valid constructor, but old java.awt.event.MouseEvent
objects can be instantiated this way. Still, I haven't found any working solution for conversion. How do I go around this?
Thanks.
When you set a handler, it sets a public property. You can get the event from that property and call handle():
Or you can use a simple "hack" to do a programmatic click on the button. Create this method in a "Util" class:
Then, to "click" on the button just call the method click passing your button as parameter.
You can generate a MouseEvent using the deprecated MouseEvent.impl_mouseEvent API. I did this previously in this forum thread for JavaFX 2.0. Note that the API is deprecated for a reason - it is private API used in the implementation of JavaFX and the API is not guaranteed to maintain the same signature or even exist in future versions (which can be evidenced because the original code I posted in the forum thread no longer compiles.
The correct solution to generating such an event is to have a public API so support this. There has already been a request filed to supply this functionality RT-9383 "Add proper constructors & factory methods to event classes, remove impl". This jira is scheduled to be completed next year for JavaFX 3.0.
In the meantime, usage of the Robot class as Sergey suggests is probably your best method.
Update: Java 8 added public constructors for javafx.event.MouseEvent and the (as indicated in Jay Thakkar's answer), you can fire such an event using Event.fireEvent (you can also fire events on Windows).
This will fire a single primary mouse click at your node: