Reputation: 11585
I need to send some events to a component in Swing, so it is handled just like any user generated, standard Swing events.
Basically, something like a macro recorder, and then executor for JEditorPane. But I need more control over the generated events.
SO, assume I have an editor, I want to:
Upvotes: 7
Views: 17961
Reputation: 167
Here is an example for JComponent to send an virtual KeyEvent to JFrame windows:
JPanel plContent = new JSubPanel();
plContent.addKeyListener(new KeyAdapter() { //receive messge from JPanel
@Override
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
if (e.getSource() == plContent) {//update main windows
updateWindowTips(); //for example else.
}
}
});
this.dispatchEvent(new KeyEvent(this, KeyEvent.KEY_PRESSED, 100, 0, KeyEvent.VK_UNDEFINED, KeyEvent.CHAR_UNDEFINED)); //dispatch event to main window.
That's all!
Upvotes: 0
Reputation: 147144
The obvious thing to do is get the EventQueue
and post events to it. That would just add the event to the queue which will get dispatched in its turn on the EDT.
java.awt.Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(event);
Someone claimed yesterday the Opera and Safari do their own thing and don't give the required permission to untrusted code.
A direct way to do it is to call Component.dispatchEvent
.
Upvotes: 6
Reputation: 4994
I believe that you have to construct an instance of the event and then call
java.awt.EventQueue.dispatchEvent(event)
Set the source of the event to the desired component.
Upvotes: 2
Reputation: 39606
If you're looking for standard GUI events, then you want java.awt.Robot
If you're looking to define your own events, you're going to have to subclass the GUI classes that need to receive those events (or better, create an external controller for them), define an event class, and dispatch the events. You can use java.beans.EventHandler to dispatch, create your own handler class (I've found that more useful on occasions), or inject your events (depending on how they inherit) into the system event queue (can't find the class to do that ... I thought it was Toolkit).
However, I would do none of these. What you describe (a macro recorder) should be implemented using a controller that generates/is fed a series of application-specific action messages (look at the Command pattern).
Upvotes: 3