In Swing, how to apply KeyListener on no specific component

前端 未结 2 817
孤城傲影
孤城傲影 2020-12-18 10:46

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

相关标签:
2条回答
  • 2020-12-18 11:19

    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.

    0 讨论(0)
  • 2020-12-18 11:26

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

    0 讨论(0)
提交回复
热议问题