Creating MouseEvent in JavaFX

I need to simulate MouseEvent.MOUSE_CLICKED . I want to use the fireEvent method for a specific Node to send an event of the above type. However, I am struggling with creating one. Apparently javafx.scene.input.MouseEvent does not have a valid constructor, but old java.awt.event.MouseEvent objects can be created this way. However, I did not find any working solution for the conversion. How do I get around this?

Thanks.

+6
source share
4 answers

You can create a MouseEvent using the deprecated MouseEvent.impl_mouseEvent API. I did this earlier in this forum for JavaFX 2.0. Please note that the API is not recommended for any reason - it is a private API used in the JavaFX implementation, and the API is not guaranteed to support the same signature or even exist in future versions (which can be confirmed since the source code I posted in the forum topic no longer compiles.

The correct solution to create such an event is to support a public API in order to support this. A request has already been submitted to provide this functionality RT-9383 "Add suitable constructors and factory methods for event classes, remove them." This jira is planned to be completed next year for JavaFX 3.0.

In the meantime, using the Robot class, as Sergey suggests, is probably your best method.


Update: Java 8 added public constructors for javafx.event.MouseEvent and (as stated in Jay Takkar's answer), you can fire such an event using Event.fireEvent (you can also fire events on Windows ).

+8
source

This will result in one single click on your node:

 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)); 
+12
source

Or you can use a simple β€œhack” to programmatically click a button. Create this method in the "Util" class:

 public static void click(javafx.scene.control.Control control) { java.awt.Point originalLocation = java.awt.MouseInfo.getPointerInfo().getLocation(); javafx.geometry.Point2D buttonLocation = control.localToScreen(control.getLayoutBounds().getMinX(), control.getLayoutBounds().getMinY()); try { java.awt.Robot robot = new java.awt.Robot(); robot.mouseMove((int)buttonLocation.getX(), (int)buttonLocation.getY()); robot.mousePress(InputEvent.BUTTON1_MASK); robot.mouseRelease(InputEvent.BUTTON1_MASK); robot.mouseMove((int) originalLocation.getX(), (int)originalLocation.getY()); } catch (Exception e) { e.printStackTrace(); } } 

Then, in order to "click" on the button to simply call the method, click the transfer button of your button as a parameter.

+2
source

When you install the handler, it sets the public property. You can get an event from this property and call handle ():

 button1.setOnMouseClicked().... the corresponding property is button1.onMouseClickedProperty().get().handle(me);//where me is some MouseEvent object 
+1
source

Source: https://habr.com/ru/post/920845/


All Articles