Length of text in jTextField
1 posts in topic
Flat View  Flat View

Posted By:   Akash_Srivastava
Posted On:   Monday, April 15, 2002 03:11 AM

How can i restrict the number of characters to be entered in a jTextField.For Example if i want only 4 characters in a text field ,Text field should not accept more than 4 characters .

Re: Length of text in jTextField

Posted By:   Anonymous  
Posted On:   Monday, April 15, 2002 04:56 AM

You just need to associate a new Document model to your JtextField

class LimitSizeTextField extends JTextField {

public LimitSizeTextField(int cols) {
public LimitSizeTextField() {

protected Document createDefaultModel() {
return new LimitedDocument();

class LimitedDocument extends PlainDocument {
private int TEXT_MAXIMUM_SIZE = 4;
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {

if (str == null) return;
if (getLength() >= TEXT_MAXIMUM_SIZE ) return;
super.insertString(offs, str, a);
About | Sitemap | Contact