The JEditorPane Class

JEditorPane is an extension of JTextComponent capable of displaying various types of content, such as HTML and RTF. It is not intended to be used as a full-featured web browser, but it can be used to view simple HTML and is ideal for integrating online help into Java applications.

JEditorPanes work closely with EditorKit objects. An EditorKit plugs into the editor pane to customize it for a particular content type. Without an EditorKit telling it how to work, a JEditorPane can’t function. We discuss EditorKit in the next section.

Figure 23-1 shows the JEditorPane in action, displaying a portion of the Javadoc for the JEditorPane class. Here’s the code:

JEditorPane showing an HTML page

Figure 23-1. JEditorPane showing an HTML page

// HTMLExample.java // import javax.swing.*; import javax.swing.event.*; import java.io.*; public class HTMLExample { public static void main(String[] args) { JEditorPane pane = null; try { pane = new JEditorPane(args[0]); } catch (IOException ex) { ex.printStackTrace(System.err); System.exit(1); } pane.setEditable(false); // Add a hyperlink listener. final JEditorPane finalPane = pane; pane.addHyperlinkListener(new HyperlinkListener( ) { public void hyperlinkUpdate(HyperlinkEvent ev) { try { if (ev.getEventType( ) == HyperlinkEvent.EventType.ACTIVATED) finalPane.setPage(ev.getURL( )); } catch (IOException ex) { ex.printStackTrace(System.err); } } }); JFrame frame = ...

Get Java Swing, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.