Reputation: 11
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.
Upvotes: 0
Views: 5071
Reputation: 324197
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.
Upvotes: 0
Reputation: 2649
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!
Upvotes: 1
Reputation: 1976
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);
}
}
Upvotes: 0