So I searched all over internet and in every single topic I found this solution for limitting JTextField input.
public class FixedDocument extends PlainDocument {
private int limit;
// optional uppercase conversion
private boolean toUppercase = false;
FixedDocument(int limit) {
super();
this.limit = limit;
}
FixedDocument(int limit, boolean upper) {
super();
this.limit = limit;
toUppercase = upper;
}
public void insertString (int offset, String str, AttributeSet attr) throws BadLocationException {
if (str == null){
return;
}
if ((getLength() + str.length()) <= limit) {
if (toUppercase) str = str.toUpperCase();
super.insertString(offset, str, attr);
}
}
}
but I have a problem with that code. This code line "super.insertString(offset, str, attr);" gives me error:
no suitable method found for insertString(int,java.lanf.String,javax.print.attribute.AttributeSet)
method javax.swing.text.PlainDocument.insertString(int,java.lang.String,javax.text.AttributeSet) is not applicable
(actual argument javax.printattribute.AttributeSet cannot be converted to javax.swing.text.AttributeSet by method invocation conversion)
anyone got any ideas what I am doing wrong here?
Your problem is that your importing the wrong AttributeSet class. You are importing javax.print.attribute.AttributeSet
, when you should be importing javax.swing.text.AttributeSet
, and the error message pretty much tells you this. Again, myself, I'd use a DocumentFilter for this as that is what it was built for.