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?
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
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With