tags:

views:

89

answers:

2

Some operating systems generate keyPressed events more quickly than my application can handle them. My first thought was to not perform the action if the calls are too close together, with something like this:

public void actionPerformed(ActionEvent e) {
    long now = System.currentTimeMillis();
    if(now - lastCall < 150) {
        System.out.println("dropping event");
    }
    else {
        lastCall = now;
    }
}

Unfortunately despite the event dropping, the application still locks up and builds up tons of events in the queue. Is there a way I can drop events at a lower level? I think by the time they get to my action listener above, it's too late to save the application from locking up. Thanks for your help!

EDIT: I should also mention that the listener is part of an AbstractAction that is associated with a menu item.

+2  A: 

i'm not sure if this actually helps, but maybe you should do it like this:

public void actionPerformed(ActionEvent e) {
    e.consume();
    long now = System.currentTimeMillis();
    if(now - lastCall < 150) {
        System.out.println("dropping event");
    }
    else {
        lastCall = now;
    }
}

http://java.sun.com/j2se/1.4.2/docs/api/java/awt/event/InputEvent.html#consume()

fin
I like the idea, but consume() is protected!
Yuvi Masory
Although I could conceivably use a KeyListener instead of an AbstractAction, since consume() is public for KeyEvents. I'd like to avoid that however since the action is associated nicely with a menu item, but it's an avenue. Thanks again.
Yuvi Masory
+1  A: 

If your app is unable to respond in time to keypresses, I would take the time-consuming section out-of-band and process in a separate thread.

Then you can build a queue of keypresses and bin duplicates etc. if required, or perform other intelligent filtering on it. This is all application specific, but the core of it seems to be that you have heavy-duty processing in your GUI event processing.

Brian Agnew
Thanks for the feedback. The code being run in actionPerformed really isn't intensive at all. In fact even if replace it all with one print line it still happens. Even if I cahnge the coalescing time in the code above to 1000 milliseconds, the program still hangs. On the other hand, if you hit the key as fast as you can (say 10 times a second), it runs fine. The events are taking too long to get to the action listener, by the time they get there the pipes are already "clogged" and dropping the event like in the code above doesn't help. :-\
Yuvi Masory