Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import javax.swing.JTextField;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.JTextComponent;

public class Main {
    public static void main(String[] argv) {
        JTextComponent textComponent = new JTextField();
        AbstractDocument doc = (AbstractDocument) textComponent.getDocument();
        doc.setDocumentFilter(new FixedSizeFilter(10));
    }
}

class FixedSizeFilter extends DocumentFilter {
    int maxSize;

    public FixedSizeFilter(int limit) {
        maxSize = limit;
    }

    public void insertString(DocumentFilter.FilterBypass fb, int offset, String str, AttributeSet attr)
            throws BadLocationException {
        replace(fb, offset, 0, str, attr);
    }

    public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String str, AttributeSet attrs)
            throws BadLocationException {
        int newLength = fb.getDocument().getLength() - length + str.length();
        if (newLength <= maxSize) {
            fb.replace(offset, length, str, attrs);
        } else {
            throw new BadLocationException("New characters exceeds max size of document", offset);
        }
    }
}