Using JEditorPane for HTML viewing
Posted on 1999-07-09
I need an HTML viewer for my Java application/applet. I was able to use JEditorPane for that purpose with the following code:
documentText = new JEditorPane();
The HTML gets constructed in my program on the fly, that is what I have is a String containing some HTML text.
There are two ways to display HTML in the pane, either using setPage(URL) or setText(String) methods.
Since I have a String it is natural to use the second method. When I use it the HTML displays correctly but I am unable to traverse the links in the document. All the links are local, that is they point to some location inside the document. In order to traverse the liks I have the folloing Listener (I've copied it from JDK documentation):
class Hyperactive implements HyperlinkListener
public void hyperlinkUpdate(HyperlinkEvent e)
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED)
JEditorPane pane = (JEditorPane) e.getSource();
if (e instanceof HTMLFrameHyperlinkEvent)
HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent)e;
HTMLDocument doc = (HTMLDocument)pane.getDocument();
catch (Throwable t)
What happens is that when I click on a link, the hyperlinkUpdate() method gets invoked and when it reaches the line
it throws an exception since e.getURL() returns null. The reason being (I suppose) the fact that the documtn was created from a strin not from a URL.
The question is how to solve this problem.
One solution would be to store the document in a file and construct a URL for that file or define a new protocol which points to a String in memory but neither of those solutions (they work fine for an application) works for an applet. So I would like to be able to display an HTML string in memory using setText() and be able to traverse the links inside that document.