devxlogo

Numeric only TextField

Numeric only TextField

Question:
Is there is a way to create a text field that only accepts numeric input?

Answer:
There are probably a couple of a ways to go about doing this. Themethod you choose will depend on your exact requirements. For someapplications, it might suffice to simply trap all key events andfilter out those characters that are not digits. But what do you doif you want to allow floating point numbers? And what about pastedtext? A general purpose solution can be achieved by using theSwing classes, which were designed to allow you to customize in the way you’ve asked about.

JTextComponent is the superclass of JTextField and encapsulates adivision between model and view. JTextComponent handles the displaytasks or view of its model. The model represents the text to display,which can be shared between multiple components, and is defined by theDocument interface. All changes to the model are signalled to theJTextComponent through DocumentEvents. Since the Document interfacetracks the changes to the text content, it is the best place to handlethe filtering of input.

In the following code example, I have subclassed PlainDocument andoverridden its insertString() method in NumberFilterDocument. Allchanges to the Document are passed through insertString(), which makesit a good place to do data validation. Before inserting a string intothe Document, you want to make sure that the resulting text is a validnumerical entry. Therefore we first store the outcome in a scratchStringBuffer and test it with Double.parseDouble(). If aNumberFormatException is thrown, we reject the string. If noexception is thrown, we go ahead and insert the string into theDocument.

import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.text.*;public class NumberField extends JTextField {  public class NumberFilterDocument extends PlainDocument {    private StringBuffer __scratchBuffer;    public NumberFilterDocument() {      __scratchBuffer = new StringBuffer();    }    public void insertString(int offset, String text, AttributeSet aset)      throws BadLocationException     {      if(text == null)        return;      __scratchBuffer.setLength(0);      // Reject all strings that cause the contents of the field not      // to be a valid number (i.e., string representation of a double)      try {        __scratchBuffer.append(getText(0, getLength()));        __scratchBuffer.insert(offset, text);        // Kludge: Append a 0 so that leading decimal points        // and signs will be accepted        __scratchBuffer.append('0');      } catch(BadLocationException ble) {        ble.printStackTrace();        return;      } catch(StringIndexOutOfBoundsException sioobe) {        sioobe.printStackTrace();        return;      }      try {        Double.parseDouble(__scratchBuffer.toString());      } catch(NumberFormatException nfe) {        // Resulting string will not be number, so reject it        return;      }      super.insertString(offset, text, aset);    }  }  public NumberField(int columns) {    super(columns);    setDocument(new NumberFilterDocument());  }  public static void main(String[] args) {    JFrame frame = new JFrame("Number Field");    WindowListener exitListener;    exitListener = new WindowAdapter() {      public void windowClosing(WindowEvent e) {        Window window = e.getWindow();        window.setVisible(false);        window.dispose();        System.exit(0);      }    };    frame.addWindowListener(exitListener);    frame.getContentPane().add(new NumberField(10), BorderLayout.CENTER);    frame.pack();    frame.setVisible(true);  }}
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist