How can we make JTextField accept only numbers in Java?



In this article, we will learn to make a JTextField accept only numbers in Java. By default, a JTextField can allow numbers, characters, and special characters. Validating user input that is typed into a JTextField can be difficult, especially if the input string must be converted to a numeric value such as an int.

Different Approaches

The following are the two different approaches for making a JTextField accept only numbers in Java:

Using a KeyListener

The KeyListener interface handles keyboard events, making it straightforward to validate input as the user types.

Adds a key listener to the text field that triggers when keys are pressed.

tf.addKeyListener(new KeyAdapter() {
    public void keyPressed(KeyEvent ke) {

The getText() method gets the current text from the text field and stores the length of the current text.

String value = tf.getText();
int l = value.length();

It checks if the key pressed is a numeric digit. If the value entered is numeric, it allows editing.

if (ke.getKeyChar() >= '0' && ke.getKeyChar() <= '9') {
    tf.setEditable(true);
    label.setText("");
} 

This else statement runs when the key pressed is not a numeric digit. Disables editing temporarily by setting setEditable(false) and displays an error message.

else {
   tf.setEditable(false);
   label.setText("* Enter only numeric digits(0-9)");
}

Example

Below is an example of making a JTextField accept only numbers in Java using KeyListener:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTextFieldValidation extends JFrame {
   JTextField tf;
   Container container;
   JLabel label;
   public JTextFieldValidation() {
      container = getContentPane();
      setBounds(0, 0, 500, 300);
      tf = new JTextField(25);
      setLayout(new FlowLayout());
      container.add(new JLabel("Enter the number"));
      container.add(tf);
      container.add(label = new JLabel());
      label.setForeground(Color.red);
      setDefaultCloseOperation(EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      tf.addKeyListener(new KeyAdapter() {
         public void keyPressed(KeyEvent ke) {
            String value = tf.getText();
            int l = value.length();
            if (ke.getKeyChar() >= '0' && ke.getKeyChar() <= '9') {
               tf.setEditable(true);
               label.setText("");
            } else {
               tf.setEditable(false);
               label.setText("* Enter only numeric digits(0-9)");
            }
         }
      });
      setVisible(true);
   }
   public static void main(String[] args) {
      new JTextFieldValidation();
   }
}

Output

Using DocumentFilter

A DocumentFilter lets you capture and change text before it's placed in the JTextField. This method adds to the JTextField's Document model directly.

The getDocument() method gets the document model of the text field. The DocumentFilter() method creates a new filter that will intercept all text modifications.

((AbstractDocument) tf.getDocument()).setDocumentFilter(new DocumentFilter() {

Called when text is inserted into the document. Returns true if the input string contains only numeric characters using the "\d+" regular expression.

@Override
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
        throws BadLocationException {
        if (string.matches("\d+")) {

If validation passes, the super.insertString() allows the text to be inserted.

super.insertString(fb, offset, string, attr);
label.setText("");

The replace() method is called when text is being replaced:

@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
        throws BadLocationException {

Example

Below is an example of making a JTextField accept only numbers in Java using DocumentFilter:

import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class JTextFieldValidation extends JFrame {
   JTextField tf;
   Container container;
   JLabel label;
   public JTextFieldValidation() {
      container = getContentPane();
      setBounds(0, 0, 500, 300);
      tf = new JTextField(25);
      setLayout(new FlowLayout());
      container.add(new JLabel("Enter the number"));
      container.add(tf);
      container.add(label = new JLabel());
      label.setForeground(Color.red);
      setDefaultCloseOperation(EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      ((AbstractDocument) tf.getDocument()).setDocumentFilter(new DocumentFilter() {
         @Override
         public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
            if (string.matches("\d+")) {
               super.insertString(fb, offset, string, attr);
               label.setText("");
            } else {
               label.setText("* Enter only numeric digits (0-9)");
            }
         }
         @Override
         public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
            if (text.matches("\d+")) {
               super.replace(fb, offset, length, text, attrs);
               label.setText("");
            } else {
               label.setText("* Enter only numeric digits (0-9)");
            }
         }
      });
      setVisible(true);
   }
   public static void main(String[] args) {
      new JTextFieldValidation();
   }
}

Output

Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-05-08T18:45:58+05:30

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements