Search code examples
javaswinghyperlinkjeditorpanestyleddocument

Appending hyperlinks to JEditorPane


I've got a program outputs some URLs to a JEditorPane. I want the URLs to be hyperlinks. The program will basically output the URLS to the JEditorPane as if it were a log.

I've got it somewhat working, but it's not hyperlinking the URLs.

Here's the code I have:

JEditorPane editorPane = new JEditorPane();
editorPane.setEditorKit(JEditorPane.createEditorKitForContentType("text/html"));
editorPane.setEditable(false);
editorPane.addHyperlinkListener(new HyperlinkListener() {
    //listener code here
});

//some other code here

StyledDocument document = (StyledDocument) editorPane.getDocument();

String url = "http://some url";
String newUrl = "\n<a href=\""+url+"\">"+url+"</a>\n";
document.insertString(document.getLength(), "\n" + newUrl + "\n", null);

Instead of http://example.com/ it's outputting:

<a href="http://example.com/">http://example.com/</a>

If I don't use a StyledDocument and just do editorPane.setText(newUrl) it does correctly hyperlink the URLs, but it has the obvious problem that setText will replace whatever was already there.


Solution

  • When you use editorPane.setText(), the method will use the editor kit to insert the string. That means it will analyze it, style it and then use document.insertString() with the appropriate styles to create the expected effect.

    If you call document.insertString() directly, you're circumventing the editor kit -> no styling. Have a look at the source code for setText() to see how it's done: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/javax/swing/JEditorPane.java#JEditorPane.setText%28java.lang.String%29

    Because of copyright, I can't copy the code here. This should get you started:

    Document doc = editorPane.getDocument();
    EditorKit kit = editorPane.getEditorKit();
    StringReader r = new StringReader(newUrl);
    kit.read(r, doc, doc.getLength());