i'm doing some tests with the java awt event queue, posting events.
ActionEvent event = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "EVENT");
try {
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(event);
} catch (SecurityException e) {
e.printStackTrace();
}
Then in my JFrame, there is a event listener:
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand() == "EVENT") {
System.out.println("Event received");
}
}
the trouble is the event i've posted in the queue did not get dispatched to the actionPerformed() listener.
i did further tests: in my class constructor:
long mask = 0xffffffffffffffffL;
Toolkit.getDefaultToolkit().addAWTEventListener(this, mask);
and the event listener:
private HashMap<Integer, Integer> seen = new HashMap<>();
@Override
public void eventDispatched(AWTEvent event) {
if(seen.containsKey(event.getID()))
seen.replace(event.getID(), seen.get(event.getID())+1);
else {
System.out.println(event.getID());
if(event instanceof ActionEvent)
System.out.println(((ActionEvent) event).getActionCommand());
seen.put(event.getID(), 1);
}
}
i used a hashmap as the number of events received is rather overwhelming, hence i simply print the unique ones. this time round i did get a response
1001
EVENT
in the event listener eventDispatched(), but not in the action listener actionPerformed(). and if i were to post the event from a different thread e.g.
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
ActionEvent event = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "EVENT");
try {
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(event);
} catch (SecurityException e) {
e.printStackTrace();
}
}
});
thread.start();
even the event listener did not receive the event.
my question is then, is there any way that i can post an ACTION_PERFORMED event to the EDT (event dispatcher thread) event queue and have it processed in actionPerformed(ActionEvent e) or some such listeners from a different thread? Thanks in advance!
edit: i did try to replace the event queue with a custom queue, that works, but is there a way to do the same with the standard event queue and EDT?