Editing HTML

Generally, editor kits serve as a collection point for everything you would need to read, write, edit, and display some type of content. The HTMLEditorKit in particular serves as just such a collection point for HTML content. In addition to the HTMLEditorKit class proper, several supporting classes aid in the process of reading HTML, displaying it in the framework of JEditorPane, and writing it to a stream. Specifically, we look at the javax.swing.text.html.parser package and the HTMLWriter class. The APIs for this section remain a bit opaque, but as we mentioned earlier, each new release of the SDK comes with increased support, functionality, and openness.

If you’re not interested in the hows and wheres of reading and writing HTML, but still want to be able to edit HTML documents, go ahead and dive into this example. We extend the SimpleEditor from earlier in this chapter to support two things:

  • More HTML actions, including horizontal rules, images, and hyperlinks

  • A Save menu item to write the document as HTML

To get started, Figure 23-8 is a screenshot of our editor in action. The document you see was created from scratch using the editor.

The SimpleEditor extended to support HTML

Figure 23-8. The SimpleEditor extended to support HTML

Here’s the HTML generated when you save the document:

<html> <head> </head> <body> <p> This is some simple text. </p> <hr> And <a href="http://www.ora.com">this is a link</a>. <p> ...

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.