JTextField textField = new JTextField(); textField.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { // perform an action when a key is pressed } public void keyTyped(KeyEvent e) { // perform an action when a key is typed } public void keyReleased(KeyEvent e) { // perform an action when a key is released } });
public class MyTextField extends JTextField { public MyTextField() { addKeyListener(new KeyAdapter() { public void keyTyped(KeyEvent e) { char c = e.getKeyChar(); if (!Character.isDigit(c)) { e.consume(); } } }); } }In this example, we have extended the JTextField class to create a custom text field. We have overridden the keyTyped() method of KeyAdapter class to perform a specific action. In this case, we have restricted the user from typing non-numeric characters by consuming the input event if the character is not a digit.