Jared
Jared

Reputation: 2133

Java scrollToReference causes exception in JEditorPane

I have a JEditorPane with a custom html document (not from URL) inside a JScrollPane, and a JTextField so that the user can enter text that will then be highlighted in the editor pane. In the textfield's keyPressed event, I search the document for the text, surround it with:

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

to highlight the background, then set the new text to the JEditorPane. This all works fine, but I also want to scroll the pane to the newly highlighted text. So in the changedUpdate method of the editor pane's documentListener, I add:

pane.scrollToReference("spot"); 

This call throws an ArrayIndexOutOfBoundsException inside BoxView.modelToView. The method finds my "spot" reference in the text, but I'm thinking that perhaps the view hasn't been updated with the new text yet, so when it tries to scroll there, it fails.

I can't get a reference to the view, and I can't seem to find an event to listen for that signifies that the JEditorPane's view is completely updated. Any ideas?

Thanks,

Jared

Upvotes: 2

Views: 455

Answers (1)

mKorbel
mKorbel

Reputation: 109823

JScrollPane#scrollToReference(java.lang.String reference) talking about String referennce to URL,

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

then all examples around showing the following workaround

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) {
        }
    }
}

Upvotes: 3

Related Questions