Feb 07

To restrict the number of characters that the user can enter into a text field can be achieved by either using a JFormattedTextField or using a custom Document with any JTextComponent.

To implement this using a JFormattedTextFiled is simply a matter of specifying the appropriate MaskFormatter to meet your requiremenets.

JTextField field = new JFormattedTextField(new MaskFormatter("***"));

The following class gives an example of how a custom Document can be implemented for use in any text component.

public class FixedSizeDocument extends PlainDocument
{
   private int max = 10;
   
   public FixedSizeDocument(int max) 
   { 
        this.max = max; 
   } 

   @Override
   public void insertString(int offs, String str, AttributeSet a)
      throws BadLocationException
   {
      // check string being inserted does not exceed max length
	   
      if (getLength()+str.length()>max)
      {
         // If it does, then truncate it
    	  
         str = str.substring(0, max - getLength());
      }
      super.insertString(offs, str, a);
   }
}

You can then use this class with your JTextField for example using the following

field.setDocument(new FixedSizeDocument(5));

written by objects \\ tags: , , , , ,