javaswingkeyeventawt-eventqueue

Prevent AWT Event Queue from overloading


I have coded a Swing GUI, which uses KeyAccelerators on JMenuItems. Pressing the keys that trigger the Accelerator for a longer time causes the EventQueue to stack commands and blocking the GUI. I want the AWT Event Queue not to have more than one (or two) KeyEvents with Control Modifier in it. I tried this:

         AWTEvent awtevent = Toolkit.getDefaultToolkit()
                        .getSystemEventQueue().peekEvent();
                if (awtevent != null) {
                    String paramString = awtevent.paramString();
                    if ((paramString.indexOf("modifiers=Ctrl") != -1 && ((KeyEvent) event)
                            .isControlDown())) {
                        ((KeyEvent) event).consume();
                    } else if (paramString.indexOf("modifiers=Ctrl") != -1
                            && (paramString.indexOf("keyChar=Undefined") != -1)) {
                        ((KeyEvent) event).consume();

                    }
                }

But its very unreliable as it sometimes consumes an Event that shouldnt be consumed.


Solution

  • You cannot reliably do this from the outside. It is not thread-safe to manipulate the event queue from outside the event-dispatch thread, and you cannot execute a task on the event dispatch thread that that mucks with events posted prior to that task itself being processed. You could maybe push a cleanup task onto the queue every second or two that would handle yet-to-be-processed events, but ... just don't.

    If you want to filter AWT / Swing events then you need to install your own event queue, which is easier than it may sound. You may find this article to be instructive.