JTextFieldLimit.java Source code

Java tutorial

Introduction

Here is the source code for JTextFieldLimit.java

Source

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

class JTextFieldLimit extends PlainDocument {
    private int limit;

    JTextFieldLimit(int limit) {
        super();
        this.limit = limit;
    }

    public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
        if (str == null)
            return;

        if ((getLength() + str.length()) <= limit) {
            super.insertString(offset, str, attr);
        }
    }
}

public class Main {
    public static void main(String[] argv) {

        JTextField textfield1 = new JTextField(15);
        textfield1.setDocument(new JTextFieldLimit(10));
    }
}