views:

624

answers:

3

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?

+2  A: 

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

camickr
but how would I obtain the actual change?
Geo
You get all the necessary information out of the `DocumentEvent` passed along with each listener method: here you will find the type of change as well as the offset into the document where the change started which, together with the length of the change, tell you the affected portion of the document. The event processing mechanism assures that these values are still correct (i.e., the document will not have changed even more) while the listener methods are executed.
Thomas
+2  A: 

In the DocumentListener interface, you have methods like getOffset() and getLength() which you could use to retrieve the actual change.

Hopes this helps you

John Doe
+2  A: 

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());
Russ Hayward