Pregunta

I want to clear text field when the escape is pressed.

I added KeyListener to the JTextField

bondIDTextField.addKeyListener(new KeyListener() {

            @Override
            public void keyTyped(KeyEvent e) {

                if( e.getKeyCode() ==   KeyEvent.VK_ESCAPE)
                    ((JTextField)e.getSource()).setText("");

            }

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

            }

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

            }
        });
¿Fue útil?

Solución

Try this code.it's working

    bondIDTextField.addKeyListener(new KeyAdapter() {
    @Override
    public void keyPressed(KeyEvent e) {
        if (e.getKeyChar() == KeyEvent.VK_ESCAPE) {
            ((JTextField)e.getSource()).setText("");
        }
    }
}
);

Otros consejos

Maybe use Key Bindings/input maps instead of a key listener?

Check out: Responding to Button using KeyBIndings

And inside the action performed just clear out your text field contents

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top