Search code examples
javaswingeventsjeditorpane

What JEditorPane event should I create a listener for?


Suppose I have a JEditorPane in a JPanel. I want to be able to execute a callback each time the user enters/pastes text in the JEditorPane component. What type of listener should I create?


Solution

  • One way of doing this is to create a custom Document and override the insertString method. For example:

    class CustomDocument extends PlainDocument {
        @Override
        public void insertString(int offset, String string, AttributeSet attributeSet)
                throws BadLocationException {
            // Do something here
            super.insertString(offset, string, attributeSet);
        }
    }
    

    This allows you to find out what is inserted and veto it if you wish (by not calling super.insertString). You can apply this document using this:

    editorPane.setDocument(new CustomDocument());