简体   繁体   English

模拟MouseEvent,KeyEvent等

[英]Simulate MouseEvent, KeyEvent, etc

I'm working on an application running on Java in a headless environment. 我正在研究在无头环境中的Java上运行的应用程序。 I'm handling all input and output through custom classes; 我正在通过自定义类处理所有输入和输出; my root JPanel is drawing to a BufferedImage which is then presented to the user. 我的根JPanel正在绘制到BufferedImage ,然后将其呈现给用户。 However, I'm having trouble passing MouseEvents to allow the JPanel and its children to handle them. 但是,我在传递MouseEvents以允许JPanel及其子代处理它们时遇到麻烦。

Currently, the constructor of my main class, a child of JPanel , uses: 当前,我的主类的构造函数( JPanel的子代)使用:

this.enableInputMethods(true);
this.enableEvents(~0);

Then, in onMouseDown(MouseEvent e) and friends (which do get executed): 然后,在onMouseDown(MouseEvent e)和朋友( 确实执行)中:

dispatchEvent(e);

I've also tried processEvent(e) and processMouseEvent(e) , but to no avail. 我也尝试过processEvent(e)processMouseEvent(e) ,但无济于事。

I'm generating the MouseEvent using the JPanel subclass as the source, and MOUSE_PRESSED and its friends as the ID. 我正在使用JPanel子类作为源,并使用MOUSE_PRESSED及其朋友作为ID来生成MouseEvent

Is there anything else I can do either in the constructor or the event handler that will allow the JPanel to process the event as a normal event, passing it off to its children and firing any ActionEvents and focus changes? 我还可以在构造函数或事件处理程序中做些其他事情,以允许JPanel将事件作为正常事件处理,将其传递给子事件并触发任何ActionEvents和焦点更改吗?

I've got a workaround that I'm currently implementing, manually creating the ActionEvents and keeping track of the currently focused component. 我有一个目前正在实施的解决方法,手动创建ActionEvents并跟踪当前关注的组件。 I'm working on passing MouseEvents down to child components at the moment but here's what I've got. 目前,我正在努力将MouseEvents传递给子组件,但这就是我所拥有的。

Component c = findComponentAt(e.getX(), e.getY());
if(c!=null){
    ActionEvent ae = new ActionEvent(c,ActionEvent.ACTION_PERFORMED,"");
    ActionListener[] listeners = c.getListeners(ActionListener.class);
    for(ActionListener l:listeners){
        l.actionPerformed(ae);
    }
    if(c.isFocusable()) setFocusedComponent(c);
}

Admittedly, it's pretty messy, but in absence of a better path to pursue I have to implement it this way. 诚然,这很混乱,但是在没有更好的追求的道路上,我必须以这种方式实现它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM