How to replace the AWT EventQueue with own implementation [closed]
Solution 1:
EventQueue has a method called push() that will do exactly what you want. Here is a little demo:
public class QueueTest {
public static void main(String[] args) throws InterruptedException, InvocationTargetException {
EventQueue eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue();
eventQueue.push(new MyEventQueue());
EventQueue.invokeAndWait(new Runnable() {
public void run() {
System.out.println("Run");
}
});
}
private static class MyEventQueue extends EventQueue {
public void postEvent(AWTEvent theEvent) {
System.out.println("Event Posted");
super.postEvent(theEvent);
}
}
}
Solution 2:
Be cautious with java 1.7. There's a bug. The solution posted by rancidfishbreath is perfect with java 1.6 but results in a Swing application that never exit with java 1.7. Under JDK 1.7, you have to install the new EvenQueue in the Event Dispatch thread ... and outside it in JDK 1.6 ... Write once, run everywhere ;-)
Here is an universal solution ... hope, 1.8 will not change it ;-)
import java.awt.AWTEvent;
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.lang.reflect.InvocationTargetException;
public class QueueTest {
public static void main(String[] args) throws InterruptedException, InvocationTargetException {
if (!isJava7Like()) setQueue();
EventQueue.invokeAndWait(new Runnable() {
public void run() {
if (QueueTest.isJava7Like()) setQueue();
System.out.println("Run");
}
});
}
private static void setQueue() {
EventQueue eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue();
eventQueue.push(new MyEventQueue());
}
private static boolean isJava7Like() {
return Float.parseFloat(System.getProperty("java.specification.version")) > 1.6;
}
private static class MyEventQueue extends EventQueue {
public void postEvent(AWTEvent theEvent) {
System.out.println("Event Posted");
super.postEvent(theEvent);
}
}
}
Solution 3:
This is fine. Extending EventQueue will give you a handle on all AWTEvents.
How will you get a handle on all the Events. List of events is as below.
[AWTEvent, BeanContextEvent, CaretEvent, ChangeEvent, ConnectionEvent, DragGestureEvent, DragSourceEvent, DropTargetEvent, FlavorEvent, HandshakeCompletedEvent, HyperlinkEvent, LineEvent, ListDataEvent, ListSelectionEvent, MenuEvent, NamingEvent, NamingExceptionEvent, NodeChangeEvent, Notification, PopupMenuEvent, PreferenceChangeEvent, PrintEvent, PropertyChangeEvent, RowSetEvent, RowSorterEvent, SSLSessionBindingEvent, StatementEvent, TableColumnModelEvent, TableModelEvent, TreeExpansionEvent, TreeModelEvent, TreeSelectionEvent, UndoableEditEvent, UnsolicitedNotificationEvent]