我应该为什么 JEditorPane 事件创建侦听器?

发布于 2024-07-26 07:34:47 字数 94 浏览 1 评论 0原文

假设我在 JPanel 中有一个 JEditorPane。 我希望每次用户在 JEditorPane 组件中输入/粘贴文本时都能够执行回调。 我应该创建什么类型的侦听器?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

荆棘i 2024-08-02 07:34:47

您可以使用 DocumentListener 来通知文档的任何更改。

由于我还不能发表评论,我只想说,尽可能使用侦听器比覆盖类更好,就像上面给出的覆盖 PlainDocument 的示例一样。

侦听器方法适用于 JTextField、JTextArea、JEditorPane 或 JTextPane。 默认情况下,编辑器窗格使用 HTMLDocument,而 JTextPane 使用 StyledDocument。 因此,通过强制组件使用 PlainDocument,您将失去功能。

如果您关心的是在将文本添加到文档之前对其进行编辑,那么您应该使用 文档过滤器

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

染火枫林 2024-08-02 07:34:47

执行此操作的一种方法是创建自定义 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());

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());
定格我的天空 2024-08-02 07:34:47

DocumentEvent 界面中,您有诸如 getOffset()getLength() 之类的方法,您可以使用它们来检索实际的更改。

希望这对您有帮助

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

Hopes this helps you

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文