如何使用 Java 以编程方式将 MouseEvent 触发到 MouseListener?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6842960/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 17:32:44  来源:igfitidea点击:

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

javaswingmouseeventjtreemouselistener

提问by michelemarcon

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

我有一个JTree与自定义关联的MouseListener(用于显示弹出窗口等)。我需要触发一个MouseEvent会被MouseListener. 我应该如何以编程方式做到这一点?

回答by jzd

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

您可以创建自己的 MouseEvent 并遍历所有侦听器并进行调用。

For example:

例如:

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

回答by Edward Dale

The Robotclass 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.

此类用于生成本地系统输入事件,以用于测试自动化、自运行演示以及需要控制鼠标和键盘的其他应用程序。Robot 的主要目的是促进 Java 平台实现的自动化测试。