JTextFieldMaxLength.java Source code

Java tutorial

Introduction

Here is the source code for JTextFieldMaxLength.java

Source

import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class JTextFieldMaxLength extends JTextField {

    public JTextFieldMaxLength(int length) {
        this(null, length);
    }

    public JTextFieldMaxLength(String text, int length) {
        super(new PlainDocumentMaxLength(length), text, length);
    }
}

class PlainDocumentMaxLength extends PlainDocument {
    private int maxLength;

    public PlainDocumentMaxLength(int maxLength) {
        this.maxLength = maxLength;
    }

    public void insertString(int offset, String str, AttributeSet a) throws BadLocationException {
        if (getLength() + str.length() > maxLength) {
            // Toolkit.getDefaultToolkit().beep();
        } else {
            super.insertString(offset, str, a);
        }
    }
}