I am trying to emulate click events in Swing using following code:
event = new MouseEvent(target, MouseEvent.MOUSE_PRESSED, ...)
java.awt.Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(event);
event = new MouseEvent(target, MouseEvent.MOUSE_RELEASED, ...)
java.awt.Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(event);
event = new MouseEvent(target, MouseEvent.MOUSE_CLICKED, ...)
java.awt.Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(event);
This works fine for most components, but the problem is if component is generating it’s own events, for example if when component receives MOUSE_PRESSED it generates some events and submits them with dispatchEvent(newEvent); With normal click event order would be:
MOUSE_PRESSED
newEvent
MOUSE_RELEASED
MOUSE_CLICKED
But because of my code order is:
MOUSE_PRESSED
MOUSE_RELEASED
MOUSE_CLICKED
newEvent
And it breaks application logic. I can easily fix it by adding Thread.sleep() calls between my postEvent() calls, but I don’t want to do it since this method is called a lot and I don’t want it to be slow, especially since current code works in 95% of cases.
How would I emulate event sequence allowing new events to be created between them? I don’t have access to component code, so I can only modify my emulation method.
You could push your own event queue which would give you total control of events. For example:
You just chain the events together so that they don’t get posted until the previous event has been dispatched allowing any intermediate events created by a component to be posted during dispatch before your next event is posted. I haven’t tried this but it should work.