Java scrollToReference 导致 JEditorPane 出现异常

标签 java swing jeditorpane

我有一个 JEditorPane,其中 JScrollPane 中有一个自定义 html 文档(不是来自 URL),还有一个 JTextField,以便用户可以输入文本,然后在编辑器 Pane 中突出显示。在文本字段的 keyPressed 事件中,我在文档中搜索文本,并将其括起来:

<a name='spot'><span style='background-color: silver'>my text</span></a> 

突出显示背景,然后将新文本设置到 JEditorPane。这一切都很好,但我还想将 Pane 滚动到新突出显示的文本。因此,在编辑器 Pane 的 documentListener 的 ChangeUpdate 方法中,我添加:

pane.scrollToReference("spot"); 

此调用会在 BoxView.modelToView 内引发 ArrayIndexOutOfBoundsException。该方法在文本中找到了我的“点”引用,但我认为 View 可能尚未使用新文本进行更新,因此当它尝试滚动到那里时,它会失败。

我无法获得对该 View 的引用,而且我似乎找不到可监听的事件来表示 JEditorPane 的 View 已完全更新。有什么想法吗?

谢谢

贾里德

最佳答案

JScrollPane#scrollToReference(java.lang.String reference)谈论 URL 的字符串引用,

Scrolls the view to the given reference location (that is, the value 
returned by the UL.getRef method for the URL being displayed).

然后所有示例都显示以下解决方法

import java.io.IOException;
import java.net.URL;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;

public class MyScrollToReference extends JDialog {
    private static final long serialVersionUID = 1L;

    public MyScrollToReference(JFrame frame, String title, boolean modal, String urlString) {
        super(frame, title, modal);

        try {
            final URL url = MyScrollToReference.class.getResource(urlString);
            final JEditorPane htmlPane = new JEditorPane(url);
            htmlPane.setEditable(false);
            JScrollPane scrollPane = new JScrollPane(htmlPane);
            getContentPane().add(scrollPane);
            htmlPane.addHyperlinkListener(new HyperlinkListener() {

                public void hyperlinkUpdate(HyperlinkEvent e) {
                    if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                        if (e.getURL().sameFile(url)) {
                            try {
                                htmlPane.scrollToReference(e.getURL().getRef());
                            } catch (Throwable t) {
                                t.printStackTrace();
                            }
                        }
                    }
                }
            });
        } catch (IOException e) {
        }
    }
}

关于Java scrollToReference 导致 JEditorPane 出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10092333/

相关文章:

Java JEditorPane

java - 如何访问和显示(打印)存储在从 Java 中的 asList View 对象创建的子 ListView 中的对象

java - Lucene 查询返回我不期望的内容

java - 在 Adempiere 的模型类中添加确认(是/否)对话框

java - JEdi​​torPane 垂直对齐

java - 带有 JRE 1.5 (IE6) 的小程序无法通过 HTTPS 打开 HTML 页面,适用于 JRE1.6

java - 从 Clojure 调用 Java

java - 在java中用正则表达式分割产生一个空元素

java - Swing 中的事件调度过滤器链

java - swing - 在 JPanel 上点击组件