Sriram
Sriram

Reputation: 2999

In Swing, how to apply KeyListener on no specific component

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 all.

Upvotes: 3

Views: 1604

Answers (2)

Eldius
Eldius

Reputation: 320

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...

Upvotes: 1

camickr
camickr

Reputation: 324207

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.

Upvotes: 6

Related Questions