Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;

public class Main extends JFrame {
    private JPanel panel = new JPanel();
    private JTextPane tpane = new JTextPane();
    private AbstractDocument abDoc;

    public Main() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Document doc = tpane.getStyledDocument();
        if (doc instanceof AbstractDocument) {
            abDoc = (AbstractDocument) doc;
            abDoc.setDocumentFilter(new DocumentSizeFilter(3));
        }
        panel.add(tpane);
        add(panel);
        pack();
    }

    public static void main(String... args) {
        new Main().setVisible(true);
    }
}

class DocumentSizeFilter extends DocumentFilter {
    int len;

    public DocumentSizeFilter(int max_Chars) {
        len = max_Chars;
    }

    public void insertString(FilterBypass fb, int offset, String str, AttributeSet a) throws BadLocationException {
        System.out.println("In DocumentSizeFilter's insertString method");
        if ((fb.getDocument().getLength() + str.length()) <= len) {
            super.insertString(fb, offset, str, a);
        }
    }

    public void replace(FilterBypass fb, int offset, int length, String str, AttributeSet a)
            throws BadLocationException {
        System.out.println("In DocumentSizeFilter's replace method");
        if ((fb.getDocument().getLength() + str.length() - length) <= len) {
            super.replace(fb, offset, length, str, a);
        }
    }
}