How to Create a Simple Swing HTML Viewer in Java
In this article
To create a simple Swing HTML viewer in Java, use a JEditorPane set to text/html content type, load your HTML into it, and place it inside a JScrollPane within a JFrame. This gives you a working viewer in about 20 lines of code, though it lacks modern CSS and JavaScript support.
Why JEditorPane Is the Default Choice
Swing's JEditorPane is the only built-in component that renders HTML without external libraries. It uses the HTMLEditorKit, which supports HTML 3.2 plus some CSS 1.0 properties. This makes it ideal for simple documents, tooltips, or log viewers. For example, the following code loads an HTML string and displays it:
JEditorPane pane = new JEditorPane();
pane.setContentType("text/html");
pane.setText("<h1>Hello</h1><p>World</p>");
pane.setEditable(false);
JScrollPane scroll = new JScrollPane(pane);
JFrame frame = new JFrame("Viewer");
frame.add(scroll);
frame.setSize(400, 300);
frame.setVisible(true);
That's the core. The component handles scrolling, selection, and basic hyperlink clicks if you add a HyperlinkListener.
How the HTML Rendering Works Under the Hood
JEditorPane delegates parsing to HTMLEditorKit, which builds a document model from the HTML stream. The kit supports tags like <b>, <i>, <table>, <ul>, and basic attributes like font and color. It does not execute JavaScript, ignore most CSS (only a few properties like font-family and color work), and has no support for flexbox or grid. Images are loaded via ImageIcon if the URL is accessible. The rendering is synchronous, so large or remote HTML can freeze the UI thread.
Step-by-Step: Building a Minimal Viewer
- Create a
JFramewith a title and default close operation. - Instantiate a
JEditorPaneand callsetContentType("text/html"). - Set the HTML content using
setText()for strings orsetPage(URL)for files/URLs. - Set
setEditable(false)to prevent accidental edits. - Wrap it in a
JScrollPaneto handle overflow. - Add the scroll pane to the frame's content pane.
- Call
setSize()andsetVisible(true).
For loading from a file, use pane.setPage(file.toURI().toURL()). This throws IOException, so handle it with a try-catch.
Handling Hyperlinks and Navigation
By default, clicking a link does nothing. Add a HyperlinkListener to respond to HyperlinkEvents. The event provides the URL and the element. A common pattern is:
pane.addHyperlinkListener(e -> {
if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
try { pane.setPage(e.getURL()); }
catch (IOException ex) { ex.printStackTrace(); }
}
});
This enables simple navigation between local files or websites. For back/forward buttons, maintain a stack of URLs yourself.
Common Problems and Their Fixes
- HTML not rendering: Ensure you called
setContentType("text/html")beforesetText(). If you usesetPage(), the content type is inferred from the URL's extension. - Blank screen with remote URLs: The default
HTMLEditorKitmay block or fail on certain MIME types. Check the URL is reachable and returnstext/html. - Images not showing: Relative paths in HTML are resolved against the document base. Use absolute URLs or set the base via
setDocumentBase(). - Freezing on large documents: The EDT is blocked. Load content in a background thread and then call
SwingUtilities.invokeLater()to update the pane. - CSS not applying: JEditorPane only supports a small subset. For modern CSS, you need a different component.
When JEditorPane Is Not Enough: Alternatives
If you need full CSS3, JavaScript, or HTML5, consider JavaFX WebView (available in Java 8+). It embeds a Chromium-based renderer and supports modern web standards. The downside is a heavier dependency and a different API. Another option is Flying Saucer (XHTML renderer) for print-quality PDFs, but it requires XML-compliant HTML. For simple text with minimal formatting, JTextPane with a StyledDocument is faster. Choose based on your content complexity: JEditorPane for basic docs, JavaFX for interactive pages.
Performance and Memory Considerations
JEditorPane is lightweight but not designed for heavy pages. Each setText() rebuilds the document, which can be slow for large strings. Reuse the pane and update only changed parts if possible. For very large HTML files, consider chunked loading or a virtualized view. Also, be aware that setPage() holds a reference to the URL and may keep connections open. Close or reset the page when done. Memory usage is proportional to the document size; a 10MB HTML file can cause significant heap usage.
Frequently Asked Questions
Can I display HTML from a string with images?
Yes, but images must be referenced by absolute URLs or file paths. The HTMLEditorKit loads images via ImageIcon and requires a valid URL. If your HTML uses relative paths, set the document base with pane.setDocumentBase(new URL("file:/...")).
Does JEditorPane support JavaScript?
No. It only renders static HTML and CSS. Any <script> tags are ignored. For JavaScript, you need JavaFX WebView or an external browser component.
How do I make links open in the default browser?
In your HyperlinkListener, use Desktop.getDesktop().browse(e.getURL().toURI()) instead of setPage(). This opens the link in the system's default browser.
Why does my HTML look different from a browser?
Because JEditorPane implements an old HTML 3.2 spec with partial CSS. Modern browsers use CSS3 and HTML5. Differences in margins, fonts, and layout are expected. For pixel-perfect rendering, use JavaFX WebView.
Can I edit HTML in the pane?
Yes, if you keep setEditable(true), the user can modify the text, but the editing is not WYSIWYG. It's plain text editing of the HTML source. For a rich text editor, use JEditorPane with HTMLEditorKit and enable the kit's editing actions.
Is JEditorPane thread-safe?
No. All Swing components must be accessed on the Event Dispatch Thread. If you load a page from a background thread, wrap the update in SwingUtilities.invokeLater().