How to programmatically fire a MouseEvent to a MouseListener with Java?

僤鯓⒐⒋嵵緔 提交于 2019-12-30 08:52:19

问题


I have a JTree with a custom associated MouseListener (for showing popup etc.). I need to fire a MouseEvent that will be caught by the MouseListener. How should I do that programmatically?


回答1:


You could create your own MouseEvent and loop through all the listeners and make the call.

For example:

MouseEvent me = new MouseEvent(tree, 0, 0, 0, 100, 100, 1, false);
for(MouseListener ml: tree.getMouseListeners()){
    ml.mousePressed(me);
}



回答2:


The Robot class might be what you're looking for.

This class is used to generate native system input events for the purposes of test automation, self-running demos, and other applications where control of the mouse and keyboard is needed. The primary purpose of Robot is to facilitate automated testing of Java platform implementations.



来源:https://stackoverflow.com/questions/6842960/how-to-programmatically-fire-a-mouseevent-to-a-mouselistener-with-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!