假设我在 JPanel 中有一个 JEditorPane。每次用户在 JEditorPane 组件中输入/粘贴文本时,我都希望能够执行回调。我应该创建什么类型的监听器?
问问题
3042 次
3 回答
5
您可以使用 DocumentListener 来通知 Document 的任何更改。
由于我还不能发表评论,我只想说尽可能使用侦听器比覆盖类更好,就像上面给出的覆盖 PlainDocument 的示例一样。
侦听器方法适用于 JTextField、JTextArea、JEditorPane 或 JTextPane。默认情况下,编辑器窗格使用 HTMLDocument,而 JTextPane 使用 StyledDocument。因此,您会通过强制组件使用 PlainDocument 来失去功能。
如果您关心的是在将文本添加到文档之前对其进行编辑,那么您应该使用DocumentFilter
于 2009-07-04T15:45:58.147 回答
3
一种方法是创建自定义 Document 并覆盖 insertString 方法。例如:
class CustomDocument extends PlainDocument {
@Override
public void insertString(int offset, String string, AttributeSet attributeSet)
throws BadLocationException {
// Do something here
super.insertString(offset, string, attributeSet);
}
}
这使您可以找出插入的内容并根据需要否决(通过不调用 super.insertString)。您可以使用以下方法应用此文档:
editorPane.setDocument(new CustomDocument());
于 2009-07-04T16:09:53.483 回答
2
在DocumentEvent接口中,您可以使用getOffset()和getLength()等方法来检索实际更改。
希望这可以帮助你
于 2009-07-04T15:55:38.830 回答