How to programmatically fire a MouseEvent to a MouseListener with Java?
Asked Answered
W

2

7

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?

Waterscape answered 27/7, 2011 at 10:39 Comment(1)
what are you tried, because JTree has implemented own Listeners invoked by Mouse and KeyBoard download.oracle.com/javase/tutorial/uiswing/events/…Upanddown
P
19

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);
}
Pruett answered 27/7, 2011 at 11:6 Comment(1)
+1 - IMO this approach is preferable to emulation of native system events.Dittman
C
3

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.

Constance answered 27/7, 2011 at 10:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.