In Swing, how to apply KeyListener on no specific component

前端 未结 2 888
孤城傲影
孤城傲影 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条回答
  •  Happy的楠姐
    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...

提交回复
热议问题