import javax.swing.*;import javax.swing.text.*;public class MaxLengthTextField extends JFrame{ private int maxLength; JTextField maxLengthTextField=null; public MaxLengthTextField(int maxLength){ this.maxLength=maxLength; this.maxLengthTextField = getTextField(maxLength); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.getContentPane().add(maxLengthTextField); this.pack(); this.setVisible(true); } public JTextField getTextField(final int maxLength){ JTextField textField=new JTextField(maxLength); PlainDocument doc=new PlainDocument(){ public void insertString(int offset, String s,AttributeSet attributeSet){ if(this.getLength()==maxLength) return; else try{ super.insertString(offset,s,attributeSet); }catch(BadLocationException e){} } }; textField.setDocument(doc); return textField; } public static void main(String[] args) { new MaxLengthTextField(5); } }