JTextField: How to limit the number of characters?

simply change your current remove method:

 @Override  
 public void remove(DocumentFilter.FilterBypass fb, int offset, int length) throws BadLocationException 
 {  

     fb.insertString(offset, "", null);
 } 

for this one:

 @Override  
 public void remove(DocumentFilter.FilterBypass fb, int offset, int length) throws BadLocationException 
 {  
     fb.remove(offset, length);
 }

it should now work.


You should make your own class that checks whether you gave more input than the maximum allowed length: See an example on http://www.java2s.com/Tutorial/Java/0240__Swing/LimitJTextFieldinputtoamaximumlength.htm.