Programming Examples

Are you a Programmer or Application Developer or a DBA? Take a cup of coffee, sit back and spend few minutes here :)

JEditorPane and Html Document

1. Introduction to JEditorPane

The JEditorPane extends from Java Swing’s JTextComponent. So it supports various document types. One can use it to display Plain document (txt), Rich Text Document (rtf) and html document. In this example, we will create a JEditorPane and load a html document into it.

2. About The Example

Below screenshot shows the JEditorPane example we create here:

Display Html in JEditorPane Example
Display Html in JEditorPane Example

The example is a simple JFrame, which houses a JEditorPane in it. The editor pane is displaying a html table above and the user can scroll the document using the scrollbars. These scrolls are useful when the document is bigger than the editor pane. Now, we will proceed with the example.

3. Html Document for the Example

In this example, we are going to load a html document in the Editor Pane. The html document is a table with heading text. We no need to go into much detail about this html content. Name this a Test.html and place it along with the java files (Found in Code Reference Section).

4. Create JEditorPane

In the below code snippet, at line 7, we create a JEditorPane via an empty constructor. By default, Java Swing keeps editor pane in the disabled state. So we make a call to setEnable to override the default state.

5. Scrolling Support

When the html document is big, the JEditorPane will not show the entire html content in it. We need to provide scrolling support for the editor pane. At line 2, we create a JScrollPane instance and set a preferred size for it. This helps in providing more container space (JFrame) for other controls. The call, setVerticalScrollBarPolicy tells we always need the vertical scrollbar. So even if the html document is small, Java Swing will display a vertical scrollbar without scroll thumb.

6. JEditorPane – Set Html Document

At line 3, we make a call to getResource method to load out html document. The URL reference refers this html document and we name it HtmlPage. Next, at line 6, the setPage method of the JEditorPane takes this html document as a parameter and displays it as the pane content. Since it is an IO action, we must handle the IOException. Note, the Scrolling support provided in the past section enables scrolling of the html page inside the editor pane.

7. Youtube Demo

8. Code Reference



Categories: Swing

Tags: , , , ,

Do you like this Example? Please comment about it for others!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.