Unable to set limit the number of characters in JTextField
I am trying to limit the number of characters entered in the JTextField...for that purpose I created a class like this:
class JTextFieldLimiter extends PlainDocument
{
private int limit;
JTextFieldLimiter(int limit)
{
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);
}
}
}
I thought this had to work fine, but the compiler is showing an error, it says:
cannot find symbol: method 开发者_C百科insertString(int,java.lang.String,javax.print.attribute.Attributeset)
location:class javax.swing.text.PlainDocument
super.insertString(offset,str,(AttributeSet) attr);
^
What's wrong with the code?
You're using the wrong AttributeSet. Check your imports.
It should be :
javax.swing.text.AttributeSet
not:
javax.print.attribute.Attributeset
Instead of creating a custom Document a better solution is to use a DocumentFilter. Then this can be used on a JTextField or JTextArea or JTextPane. Read the section from the Swing tutorial on How to Write a Document Filter for a working example.
I'd avoid using the Document or DocumentFilter if you're just wanting to limit the number of characters in a JTextField. You can just override the keyTyped() event, like this example:
txtGuess = new JTextField();
txtGuess.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
if (txtGuess.getText().length() >= 3 ) // limit textfield to 3 characters
e.consume();
}
});
This limits the number of characters in a guessing game text field to 3 characters, by overriding the keyTyped event and checking to see if the textfield already has 3 characters - if so, you're "consuming" the key event (e) so that it doesn't get processed like normal.
One of my students asked this question, and none of the other answers on StackOverflow were as short as the answer I gave them, so I thought I'd post for discussion : ). Cheers!
精彩评论