Numeric only TextField

Numeric only TextField

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

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);  }}
Share the Post:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several