问题描述
我需要模拟一个 MouseEvent.MOUSE_CLICKED
。我想使用特定 Node 的 fireEvent 方法来调度上述类型的事件。但是,我正在努力生成一个。似乎 javafx.scene.input.MouseEvent 没有有效的构造函数,但旧的 java.awt.event.MouseEvent
对象可以这样实例化。不过,我还没有找到任何可以转换的工作方案。如何解决这个问题?
谢谢。
可以使用不推荐使用的MouseEvent.impl_mouseEvent API生成MouseEvent。我以前在这个中为JavaFX 2.0做了这个。请注意,由于某种原因,API已被弃用 - 它是在实现JavaFX时使用的专用API,并且API不能保证保持相同的签名,甚至在以后的版本中也可以存在(这可以被证明是因为我在论坛线程不再编译。
生成此类事件的正确解决方案是拥有一个公共API,以支持这一点。已经有一个请求提供这个功能和(如Jay Thakkar的回答中所示),您可以使用(你也可以)。
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.
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).
这篇关于在JavaFX中生成MouseEvent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!