Search code examples
javaswingjtextfieldkeylistener

How to cast getSource() to be a JTextField?


I am making a KeyListener class so I can control any JTextField that I want, but I do not know how to get whatever JTextField I call so I can press escape and clear the JTextField? Here is my current code

private class IntegerTxtListener implements KeyListener {
    public void keyTyped(final KeyEvent e) {
            if (e.getKeyChar() < KeyEvent.VK_0
                    || e.getKeyChar() > KeyEvent.VK_9) {
                e.consume();
            }
        if (e.getKeyChar() == KeyEvent.VK_ESCAPE) {
            e.consume();
           //My Problem is Here----------------------------
            e.getSource()).setText("");
        }
    }

    @Override
    public void keyPressed(KeyEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void keyReleased(KeyEvent arg0) {
        // TODO Auto-generated method stub

    }
}

Solution

  • I think this schould work:

    if (e.getKeyChar() == KeyEvent.VK_ESCAPE) {
        e.consume();
       //My Problem is Here----------------------------
        ((JTextField)e.getSource()).setText("");
    }
    

    Just the default way of casting objects.

    But it might happen that some errors occur if e is not an instance of JTextField.
    So if you are sure that your Listener will not give a source other than JTextField object you can go this way. Otherwise you you add errorhandling /-prevention.