Creating a numeric-only JTextfield

Here’s the code for a Swing component that only accepts digits.

Main.java:

import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      getContentPane().setLayout(new GridLayout(2, 1));
 
      final JPasswordField passwordField = new JPasswordField(20);
      final JTextField textField = new JTextField(20);
      getContentPane().add(new NumberTextField(5));
      getContentPane().add(new NumberTextField(123, 7));
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      pack();
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}
 
class NumberTextField extends JTextField
{
   private NumberFormat nf;
 
   public NumberTextField(int cols) {
      super(cols);
      nf = NumberFormat.getNumberInstance();
   }
 
   public NumberTextField(int value, int cols) {
      this(cols);
      setValue(value);
   }
 
   public int getValue() {
      int n = 0;
      try {
         n = nf.parse(getText()).intValue();
      }
      catch(ParseException e) { }
      return n;
   }
 
   public void setValue(int value) {
      setText(nf.format(value));
   }
 
   protected Document createDefaultModel() {
      return new NumberDocument();
   }
 
   protected class NumberDocument extends PlainDocument {
      public void insertString(int offset, String string, AttributeSet as) 
            throws BadLocationException  {
         char [] src = string.toCharArray();
         char [] dest = new char[src.length];
         int count=0;
         for (int i=0; i < src.length; i++) {
            if (Character.isDigit(src[i])) 
               dest[count++] = src[i];
         }
         super.insertString(offset, new String(dest, 0, count), as);
      }
   }
}