Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java Language
Expertise: Beginner
Oct 18, 1999

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. The method you choose will depend on your exact requirements. For some applications, it might suffice to simply trap all key events and filter out those characters that are not digits. But what do you do if you want to allow floating point numbers? And what about pasted text? A general purpose solution can be achieved by using the Swing classes, which were designed to allow you to customize in the way you've asked about.

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

In the following code example, I have subclassed PlainDocument and overridden its insertString() method in NumberFilterDocument. All changes to the Document are passed through insertString(), which makes it a good place to do data validation. Before inserting a string into the Document, you want to make sure that the resulting text is a valid numerical entry. Therefore we first store the outcome in a scratch StringBuffer and test it with Double.parseDouble(). If a NumberFormatException is thrown, we reject the string. If no exception is thrown, we go ahead and insert the string into the Document.

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);
  }
}

DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date