Mega Code Archive

 
Categories / Java / Swing JFC
 

JTextField Max Length

import javax.swing.JTextField; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument; public class JTextFieldMaxLength extends JTextField{   public JTextFieldMaxLength(int length){     this(null,length);   }   public JTextFieldMaxLength(String text, int length){     super(new PlainDocumentMaxLength(length),text,length);   } } class PlainDocumentMaxLength extends PlainDocument{   private int maxLength;   public PlainDocumentMaxLength(int maxLength) {     this.maxLength = maxLength;   }   public void insertString (int offset, String str, AttributeSet a)     throws BadLocationException { if (getLength() + str.length() > maxLength) {      // Toolkit.getDefaultToolkit().beep();     }else{     super.insertString(offset,str,a);     }   } }