Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 460
Geo Avatar asked Nov 21 '25 09:11

Geo


2 Answers

You can use a DocumentListener to be notified of any changes to the Document.

Since I can't yet leave comments, I would just like to say that it is better to use listeners when possible than it is to override a class, like the example given above that overrides the PlainDocument.

The listener approach will work on a JTextField, JTextArea, JEditorPane or JTextPane. By default an editor pane uses a HTMLDocument and a JTextPane uses a StyledDocument. So you are losing functionality by forcing the component to use a PlainDocument.

If your concern is about editing the text before it is added to the Document, then you should be using a DocumentFilter

like image 107
camickr Avatar answered Nov 23 '25 22:11

camickr


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());
like image 32
Russ Hayward Avatar answered Nov 23 '25 23:11

Russ Hayward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!