If you wanna have everything into one only piece of code, then you can mix tim's answer with the example's approach found on the API for JTextField, and you'll get something like this:
public class JTextFieldLimit extends JTextField {
private int limit;
public JTextFieldLimit(int limit) {
super();
this.limit = limit;
}
@Override
protected Document createDefaultModel() {
return new LimitDocument();
}
private class LimitDocument extends PlainDocument {
@Override
public void insertString( int offset, String str, AttributeSet attr ) throws BadLocationException {
if (str == null) return;
if ((getLength() + str.length()) <= limit) {
super.insertString(offset, str, attr);
}
}
}
}
Then there is no need to add a Document to the JTextFieldLimit due to JTextFieldLimit already have the functionality inside.