Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generating a MouseEvent in JavaFX

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.

like image 892
XXL Avatar asked Jul 19 '12 00:07

XXL


2 Answers

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));
like image 82
Jay Thakkar Avatar answered Oct 14 '22 18:10

Jay Thakkar


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).

like image 43
jewelsea Avatar answered Oct 14 '22 17:10

jewelsea