I have to restrict the number of characters in the JTextField. I used the following code to do that but the problem is i am feeding the data to JTextField using the virtual keyboard. So the offset is set to 0 all the time. When i enter more than the specified number of characters it resets the field and start doing it from the beginning. For example if my limit is 3 characters and i am entering xyz0
my limited textbox reads the character upto z
and then clears the field and restart again. So i am left with 0
in the field. The code is as follows.
public class JTextFieldLimit extends PlainDocument {
private int limit;
public JTextFieldLimit(int limit) {
super();
this.limit = limit;
}
@Override
public void insertString( int offset, String str, AttributeSet attr ) throws BadLocationException {
if (str == null) return;
System.out.println("from document helper getLength():"+getLength());
System.out.println("from document helper str.length():"+str.length());
System.out.println("from document helper str:"+str);
System.out.println("from document helper attr:"+attr);
System.out.println("from document helper offset:"+offset);
if ((getLength() + str.length()) <= limit) {
super.insertString(offset, str, attr);
}
}
}