Generally we apply the Key Listener on specific components like text field, password fields, etc. But I would like to generalize this listener behavior to be applicable to a
Swing was designed to be used with Key Bindings which might do what you want. I would start by checking out Key Bindings. Don't forget to read the Swing tutorial for complete information.
If that doesn't help then see Global Event Listeners for a couple of suggestions.
All swing components are a JComponent. You may use all of then as a JComponent:
@Override
public void keyTyped(KeyEvent e) {
JComponent component = (JComponent) e.getSource();
// TODO Implements your action
}
You can see that this is a limited approach.
You also may work according to the class of your source:
@Override
public void keyTyped(KeyEvent e) {
Object source = (JComponent) e.getSource();
if (source instanceof JTextField) {
// TODO Implment action for JTextField
} else if (source instanceof JTextArea) {
// TODO Implment action for JTextArea
}
}
Depending on your needs you may use the Reflections API to do this...