Java Reference
In-Depth Information
The Editor Kits
You briefly saw some of the default EditorKit capabilities of TextAction objects earlier in this
chapter, in the “Using Actions with Text Components” section. The EditorKit class serves as
the mastermind for pulling together all the different aspects of the text components. It creates
documents, manages actions, and creates the visual representation of the document or View .
In addition, an EditorKit knows how to read or write the document to a stream. Each document
type requires its own EditorKit , so different ones are provided with the JFC/Project Swing
components for both HTML and RTF text, as well as plain and styled text.
The actual display of the Document contents is done through the EditorKit with the help of
a ViewFactory . For each Element of the Document , the ViewFactory determines which View is
created for that element and rendered by the text component delegate. For each different type
of element, there is a different View subclass.
Loading HTML Documents
In Chapter 15, you saw how the read() and write() methods of the JTextComponent allow you
to read in and write out content for a text component. While the LoadSave example from Listing
15-3 in Chapter 15 demonstrated this process for the JTextField , it works with all the text
components, as you would expect. The only requirement for making sure the loading and
saving is done for the proper document type is to change the editor kit for the document.
To demonstrate, here's how you could load an HTML file as a StyledDocument into a
JEditorPane :
JEditorPane editorPane = new JEditorPane();
editorPane.setEditorKit(new HTMLEditorKit());
reader = new FileReader(filename);
editorPane.read(reader, filename);
It is that easy. The content type of the component is set to be text/html and loads in the
content from filename to be displayed as HTML content. One thing worth noting is that the
loading is done asynchronously.
If you need to load the content in synchronously, so that you can wait until everything is
loaded, such as for parsing purposes, the process is a bit more involved. You need to work with
the HTML parser ( HTMLEditorKit.Parser class in javax.swing.text.html package), the parser
delegator ( ParserDelegator in the javax.swing.text.html.parser package), and the parser
callback ( HTMLEditorKit.ParserCallback ) that you get from the HTMLDocument (as an
HTMLDocument.HTMLReader ). It sounds more complicated than it really is. To demonstrate, the
following code loads a file synchronously into the JEditorPane .
reader = new FileReader(filename);
// First create empty empty HTMLDocument to read into
HTMLEditorKit htmlKit = new HTMLEditorKit();
HTMLDocument htmlDoc = (HTMLDocument)htmlKit.createDefaultDocument();
// Next create the parser
HTMLEditorKit.Parser parser = new ParserDelegator();
// Then get HTMLReader (parser callback) from document
HTMLEditorKit.ParserCallback callback = htmlDoc.getReader(0);
Search WWH ::




Custom Search