here\'s the code that i have on how to limit the character input length
class JTextFieldLimit extends PlainDocument {
private int limit;
// optional uppe
JFormattedTextField
JTextComponent txt = new JFormattedTextField( new LimitedIntegerFormatter(limit) );
txt.addPropertyChangeListener("value", yourPropertyChangeListener);
import javax.swing.text.DefaultFormatter;
import java.text.ParseException;
public class LimitedIntegerFormatter extends DefaultFormatter {
static final long serialVersionUID = 1l;
private int limit;
public LimitedIntegerFormatter( int limit ) {
this.limit = limit;
setValueClass(Integer.class);
setAllowsInvalid(false);
setCommitsOnValidEdit(true);
}
@Override
public Object stringToValue(String string) throws ParseException {
if (string.equals("")) return null;
if (string.length() > limit) throw new ParseException(string, limit);
return super.stringToValue(string);
}
}
yourPropertyChangeListener will be called with
new PropertyChangeEvent( "value", Integer oldValue, Integer newValue )
( oldValue or newValue will be null in "" text case )
after every valid edit