JTextField limit length Ok, but can't set initial text string through constructor

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
 
C

Christian Kaufhold

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?


Put the maximum length instance variable into the Document.
Then do not use createDefaultModel, but the JTextField constructor
that takes a Document.

(Then, do not subclass JTextField only for this)


JTextField2(String text, int columns)
{
super(new PlainDocument2(columns), text, columns);
}


Christian
 
L

Lovely Dola

It works! Thanks a lot!
But I have a question.
Why shouldn't subclass JTextField only for this?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top