Working with JEditorPane

In this tutorial, we will show you how to use JEditorPane class to create a simple web browser that displays simple HTML document.

JEditorPane is a kind of text area which can display various text formats. By default, JEditorPane supports HTML and RTF (Rich Text Format). However, you can build your own “editor kits” to handle specific content type. You can use setContentType() method to choose the document you want to display and setEditorKit() method to set custom editor for JEditorPane explicitly.

In practice, JEditorPane is typically used for displaying HTML only.  JEditorPane also supports RTF but very limited. You can set content for JEditorPane in the following ways:

  • Pass URL object or URL string into the constructor of JEditorPane.
  • Use setPage() method to set content of JEditorPane at runtime.
  • Pass content as a String to the setText() method.
  • Use read() and supplying an HTMLDocument object with InputStream object.

To make JEditorPane read-only, you use method setEditable(false).  When displaying HTML document, JEditorPane can detect HTML links and which link user clicks. To handle the click event on links, you need to handle HyperlinkListener event.

Example of using JEditorPane to create a simple web browser

In this example, we will create a very simple web browser to display any web page by using JEditorPane component. In this example, we are also using JButton and JTextField components.


  • Was this tutorial helpful ?
  • YesNo