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.
This will fire a single primary mouse click at your node:
import javafx.event.Event;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
Event.fireEvent(YOUR NODE, new MouseEvent(MouseEvent.MOUSE_CLICKED, 0,
0, 0, 0, MouseButton.PRIMARY, 1, true, true, true, true,
true, true, true, true, true, true, null));
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).
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