Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swing: How to create Events and dispatch them to a component?

Tags:

java

events

swing

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:

  1. capture all events sent to it, and at that point, i can store them in list, on disk, or whatver..
  2. Be able to later play those events
  3. Ideal situation, is to allow user to edit a commands which contains things like:
    "type key A, select line, delete-selection, cursor-up, line-start..."
like image 472
Ayman Avatar asked Apr 30 '09 18:04

Ayman


3 Answers

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.

like image 127
Tom Hawtin - tackline Avatar answered Sep 28 '22 05:09

Tom Hawtin - tackline


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).

like image 21
kdgregory Avatar answered Sep 28 '22 05:09

kdgregory


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.

like image 23
Gary Kephart Avatar answered Sep 28 '22 05:09

Gary Kephart