Search code examples
javaswingjtextpane

How do I limit the amount of characters in JTextPane as the user types (Java)


I need to not allow any characters to be entered after X have been typed. I need to send a beep after X characters have been typed. I know how to do this after the user presses enter, but I need to do it before the user presses enter. The approach I found from Oracle's site is to add a DocumentSizeFilter to the JTextPane. I can't get this to notify the user when they have gone over (it doesn't work until they press enter). This is a sample of what I have.

public class EndCycleTextAreaRenderer extends JTextPane
implements TableCellRenderer {

private final int maxNumberOfCharacters = 200;

public EndCycleTextAreaRenderer() {
    StyledDocument styledDoc = this.getStyledDocument();
    AbstractDocument doc;
    doc = (AbstractDocument)styledDoc;
    doc.setDocumentFilter(new DocumentSizeFilter(maxNumberOfCharacters ));

}

Solution

  • Override the insertString method of the document in the JTextPane so that it doesn't insert any more characters once the maximum has been reached.

    For example:

    JTextPane textPane = new JTextPane(new DefaultStyledDocument() {
        @Override
        public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
            if ((getLength() + str.length()) <= maxNumberOfCharacters) {
                super.insertString(offs, str, a);
            }
            else {
                Toolkit.getDefaultToolkit().beep();
            }
        }
    });
    

    Update:

    You can change your class as follows:

    public class EndCycleTextAreaRenderer extends JTextPane implements TableCellRenderer {
    
        private final int maxNumberOfCharacters = 200;
    
        public EndCycleTextAreaRenderer() {
            setStyledDocument(new DefaultStyledDocument() {
                @Override
                public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
                    if ((getLength() + str.length()) <= maxNumberOfCharacters) {
                        super.insertString(offs, str, a);
                    } else {
                        Toolkit.getDefaultToolkit().beep();
                    }
                }
            });
        }
    }