L
Lovely Dola
I have the following code that limits number of characters
that can be input to a text field. However, when I pass
an initial string to the constructor, it is not placed in
the text field. Can anyone tell me how to do that successfully
without calling setText() again?
Please forgive my poor English...
//*****************************************************************************
class JTextField2 extends JTextField {
private int maxLength;
JTextField2(String text, int columns) {
super(text, columns);
maxLength = columns;
if (maxLength <= 0) maxLength = -1;
addFocusListener(this);
}
protected Document createDefaultModel() {
return new PlainDocument2();
}
class PlainDocument2 extends PlainDocument {
public void insertString(int offset, String str, AttributeSet attr)
throws BadLocationException {
if (str == null) return;
if (maxLength == -1 || getLength() + str.length() <= maxLength) {
super.insertString(offset, str, attr);
}
}
}
}
....
// "Hello" not appears in the textfield
JTextField2 myfld = new JTextField2("Hello", 10);
myfld.setText("Hello"); // "Hello" is now placed in textfield
that can be input to a text field. However, when I pass
an initial string to the constructor, it is not placed in
the text field. Can anyone tell me how to do that successfully
without calling setText() again?
Please forgive my poor English...
//*****************************************************************************
class JTextField2 extends JTextField {
private int maxLength;
JTextField2(String text, int columns) {
super(text, columns);
maxLength = columns;
if (maxLength <= 0) maxLength = -1;
addFocusListener(this);
}
protected Document createDefaultModel() {
return new PlainDocument2();
}
class PlainDocument2 extends PlainDocument {
public void insertString(int offset, String str, AttributeSet attr)
throws BadLocationException {
if (str == null) return;
if (maxLength == -1 || getLength() + str.length() <= maxLength) {
super.insertString(offset, str, attr);
}
}
}
}
....
// "Hello" not appears in the textfield
JTextField2 myfld = new JTextField2("Hello", 10);
myfld.setText("Hello"); // "Hello" is now placed in textfield