问题
I may be missing something obvious about this in the documentation for addKeyListener, removeKeyListener, getKeyListeners or associated tutorials, but are there any guarantees about the order in which added key listeners are run? My hope is that they are run in the order in which they are added, but I don't see that this is specified anywhere.
The situation I have is that I need to add a key listener to an existing Component
and override the existing key listeners for particular keys. It seems that one should be able to do this by:
- Using
getKeyListeners
to find all the existing keylisteners. - Remove each existing key listener with
removeKeyListener
- Use
addKeyListener
to add my key listener. (This only deals with selected keypresses, and consumes the event when it does.) - Finally add back all the key listeners that were found in the first step with
addKeyListener
.
However I don't want to do this if it turns out that it won't work on particular JVMs, etc.
回答1:
I don't quite understand your situation. Relying on the order in which listeners are called seems a little bit dodgy to me.
Can you not just create a key listener wrapper class which detects when your event happens, and if appropriate than delegates the event to the wrapped listener class(es)?
I think there are better ways of achieving what you want to achieve without relying on listener ordering, unless I have misunderstood something!
回答2:
I don't know if the order is guaranteed or not.
You could modify your approach slightly to make it work in most circumstances though: keep steps 1, 2 and 3 as they are, but store the list of key listeners in your custom key listener and don't add them back to the Component's listeners.
Inside your custom listener, in each method, after having done your own processing, call the saved listener's methods. Pseudo code:
void keyPressed(event) {
// do some magic
for (listener: savedListeners)
listener.keyPressed(event);
}
回答3:
After reading through the docs, it seems like there is a guarantee that KeyEvent
s will be enqueued and will be processed sequentially. But it says nothing about the KeyListener
s. To me it infers that there will not be any guarantee of this kind, as every listeners is running as a separate thread.
So, I would vote for Phill here. Mat's suggestion is fine too.
回答4:
My hope is that they are run in the order in which they are added, but I don't see that this is specified anywhere.
No the order is not guaranteed.
I believe the currently implemented order is that all listeners (not just key listeners) are run in reverse order in which they are added.
Check out the EventListenerList class which I believe is the class used to implement this functionality.
Of course this is easily tested. You just add a couple of listeners to your component and have each listener display a message when it is invoked.
来源:https://stackoverflow.com/questions/5274172/is-the-order-in-which-keylisteners-will-be-called-guaranteed