JEditorPane

If you need a more interactive, complete implementation of HTML 3.2, you can use a javax.swing.JEditorPane. This class provides an even more complete HTML 3.2 renderer that can handle frames, forms, hyperlinks, and parts of CSS Level 1. The JEditorPane class also supports plain text and basic RTF, though the emphasis in this book will be on using it to display HTML.

JEditorPane supports HTML in a fairly intuitive way. You simply feed its constructor a URL or a large string containing HTML, then display it like any other component. There are four constructors in this class:

public JEditorPane(  )
public JEditorPane(URL initialPage) throws IOException
public JEditorPane(String url)  throws IOException
public JEditorPane(String mimeType, String text)

The noargs constructor simply creates a JEditorPane with no initial data. You can change this later with the setPage( ) or setText( ) methods:

public void setPage(URL page) throws IOException
public void setPage(String url) throws IOException
public void setText(String html)

Example 8.2 shows how to use this constructor to display a web page. JEditorPane is placed inside a JScrollPane to add scrollbars; JFrame provides a home for the JScrollPane. Figure 8.2 shows this program displaying the O’Reilly home page.

Example 8-2. Using a JEditorPane to Display a Web Page

import javax.swing.text.*; import javax.swing.*; import java.io.*; import java.awt.*; public class OReillyHomePage { public static void main(String[] args) { JEditorPane ...

Get Java Network Programming, Second 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.