views:

442

answers:

1

I need to take text from a source as plain text and display it in a JTextPane or JEditorPane. The source text is not HTML but will contain URLs between square brackets which need to be displayed and function as hyperlinks.

I've considered setting the pane's content type to text/html and surounding the url in html tags but that ends up ignoring the newline characters, which is a bad thing, and i'm not sure how to go about replacing newline characters with "<br/>". Is there an easy wat to do that?

If doing that means scanning through the whole string wouldn't it be better to just customize how the text is displayed?

So I've also considered the route that involves making my own EditorKit like starturtle mentions in this thread, but he doesn't explain how to do it. I've looked over the code in this article, but it seems like a lot of work, is this the route I should take?

Has anyone ever done this. Any recommendations? Is it better to convert to html or to customize the display?

+2  A: 

i'm not sure how to go about replacing newline characters with "<br/>". Is there an easy wat to do that?

You can do that with Java regex:

    String raw = "...";
    Pattern p = Pattern.compile("\n");
    String html = "<HTML>" + p.matcher(raw).replaceAll("<BR>") + "</HTML>" ;

I have taken the liberty of adding your HTML wrapper in for you.


edit:

For the fun of it, I've taken Oscar's point and took a stab:

    Pattern p = Pattern.compile("\\[([^\\]]*)\\]");
    raw = p.matcher(raw).replaceAll("<a href=\"$1\">$1</a>");
akf
+1 @Victor: This is correct. Processing the hyperlinks should very similar: substitute [] with <a href= etc etc . You have to process the input anyway!
OscarRyz
I had tried the string replace method and that wasn't working. this works thanks.
Victor