I want to limit the number of characters to be inserted in a JTextField to 10 character. I use a graphical interface under netbeans.thanks.
Asked
Active
Viewed 4,620 times
0
-
add a `documentListener` to you `JTextField` – Blip May 04 '15 at 10:18
-
This question was originally closed as a duplicate to this question: http://stackoverflow.com/questions/3519151/how-to-limit-the-number-of-characters-in-jtextfield. That is an old answer. The Swing API has evolved and the more current solution would be to use a DocumentFilter, so I re opened the question. – camickr May 04 '15 at 13:49
3 Answers
1
To prevent the user from entering more the 10 charaters in a textfield you can use a document.
Create a simple document by extending PlainDocument
and to change the behavior override
public void insertString(...) throws BadLocationException
This is an example
public class MaxLengthTextDocument extends PlainDocument {
//Store maximum characters permitted
private int maxChars;
@Override
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
// the length of string that will be created is getLength() + str.length()
if(str != null && (getLength() + str.length() < maxChars)){
super.insertString(offs, str, a);
}
}
}
After this, only insert your implementation in JTextField
, this way:
...
MaxLengthTextDocument maxLength = new MaxLengthTextDocument();
maxLength.setMaxChars(10);
jTextField.setDocument(maxLength);
...
And that's it!

MChaker
- 2,610
- 2
- 22
- 38
-
Quick post, I know this is old but `(getLength() + str.length() < maxChars))` should really be `(getLength() + str.length() <= maxChars))` otherwise one less character than what is set will be allowed into the text field. Thanks for the post though, just helped me out! – Swemoph Oct 09 '16 at 01:44
0
Best thing is you will get running demo ;)
class JTextFieldLimit extends PlainDocument {
private int limit;
JTextFieldLimit(int limit) {
super();
this.limit = limit;
}
JTextFieldLimit(int limit, boolean upper) {
super();
this.limit = limit;
}
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);
}
}
}
public class Main extends JFrame {
JTextField textfield1;
JLabel label1;
public static void main(String[]args){
new Main().init();
}
public void init() {
setLayout(new FlowLayout());
label1 = new JLabel("max 10 chars");
textfield1 = new JTextField(15);
add(label1);
add(textfield1);
textfield1.setDocument(new JTextFieldLimit(10));
setSize(300,300);
setVisible(true);
}
}

Sarz
- 1,970
- 4
- 23
- 43
0
Read the section from the Swing tutorial on Implementing a DocumentFilter for a more current solution.
This solution will work an any Document, not just a PlainDocument.

camickr
- 321,443
- 19
- 166
- 288