This is may be a good situation for using Key Bindings. In a second I'll get you more information on this. In general you would try to avoid use of a KeyListener as this is considered a low level a construct and may be too low for this sort of thing, and often Key Bindings are preferred (as per the Key Bindings tutorial).
Edit 1
Here you go: How to use Key Bindings
Direct quote from the Swing Tutorial:
An alternative to key bindings is using key listeners. Key listeners have their place as a low-level interface to keyboard input, but for responding to individual keys key bindings are more appropriate and tend to result in more easily maintained code. Key listeners are also difficult if the key binding is to be active when the component doesn't have focus. Some of the advantages of key bindings are they're somewhat self documenting, take the containment hierarchy into account, encourage reusable chunks of code (Action objects), and allow actions to be easily removed, customized, or shared. Also, they make it easy to change the key to which an action is bound. Another advantage of Actions is that they have an enabled state which provides an easy way to disable the action without having to track which component it is attached to.
Edit 2
Note, there are times when you will want to filter the text entered into your component, and where you would use a DocumentFilter
. I think that we are somewhat hampered by your current question since you've not yet told us what the overall goal of this functionality is. Please tell us more so that we can give you a better more complete and more correct answer.