23.6 Extending HTMLEditorKit


As a quick example of how we might extend this class to add some functionality of our own, let's look at an editor kit that spits out debugging information as we load documents. This allows us to see the steps involved in extending an editor kit, and it leaves us with a very useful tool for implementing other extensions (such as custom tags and attributes).

The first step, of course, is to create our extended editor kit. In this example, we create a debugging editor kit that spits out the styles loaded and the individual tags it passes by. Here's the code:

 // DebugHTMLEditorKit.java  // A simple extension of the HTMLEditor kit that uses a verbose ViewFactory. import javax.swing.*; import javax.swing.text.*; import javax.swing.text.html.*; import javax.swing.event.*; import java.awt.event.*; import java.awt.*; import java.io.Serializable; import java.net.*; public class DebugHTMLEditorKit extends HTMLEditorKit {   public static HTML.Tag ORA = new HTML.UnknownTag("ora");   public static AttributeSet currentAnchor;   public void install(JEditorPane paneEditor) {     super.install(paneEditor);     StyleSheet ss = getStyleSheet( );     java.util.Enumeration e = ss.getStyleNames( );     while (e.hasMoreElements( )) {       System.out.println(e.nextElement( ));     }   }   public ViewFactory getViewFactory( ) {     return new VerboseViewFactory( );   }   public static class VerboseViewFactory extends HTMLEditorKit.HTMLFactory   {     public View create(Element elem) {       System.out.print("Element: " + elem.getName( ));       Object o=elem.getAttributes( ).         getAttribute(StyleConstants.NameAttribute);       HTML.Tag kind = (HTML.Tag) o;       System.out.println(" view as: " + o);       dumpElementAttributes(elem);       return super.create(elem);     }     private void dumpElementAttributes(Element elem) {       AttributeSet attrs = elem.getAttributes( );       java.util.Enumeration names = attrs.getAttributeNames( );       while (names.hasMoreElements( )) {         Object key = names.nextElement( );         System.out.println("  " + key + " : " + attrs.getAttribute(key));       }       try {         System.out.println("  " +            elem.getDocument( ).getText(elem.getStartOffset( ),              elem.getEndOffset( )));       } catch (Exception e) { // We don't deal with null elements for now.       }     }   } }

Two methods extend HTMLEditorKit. First, we override the install( ) method to print our style information. Notice that we still call super.install( ). Without that call, we would lose the hyperlink functionality. (Sometimes you want that we'll see an example of modifying hyperlink behavior later in the chapter.)

Next, we override getViewFactory( ) to return an instance of our own factory (written as an inner class). In our case, we use the create( ) method as a springboard to dump debugging information for each document element that passes through. At the end, we return the standard view that HTMLEditorKit normally produces. It's in this method that you can send back any custom view factory you like. If you need to support a specific L&F that you can't get from a regular browser and stylesheets through HTML, a custom ViewFactory and HTMLEditorKit may be the ticket.

23.6.1 The HTMLDocument Class

While the editor kit is interesting in its own right, we can't do much beyond displaying web pages without looking at the HTMLDocument class. This class supports the basic structure of HTML pages. From this class you can view and manipulate the content of a given web page. Not coincidentally, this turns out to be handy for editing documents we plan to save as HTML.

23.6.1.1 Properties

The properties for HTMLDocument shown in Table 23-12 help define the appearance and behavior of the document.

Table 23-12. HTMLDocument properties

Property

Data type

get

is

set

Default value

base

URL

·

 

·

null

parser1.3

HTMLEditorKit.Parser

·

 

·

null*

preservesUnknownTags

boolean

·

 

·

true

styleSheet

StyleSheet

·

     

tokenThreshold

int

·

 

·

Integer.MAX_VALUE

1.3since 1.3

*Set by HTMLEdtiorKit.createDefaultDocument

See also properties from the DefaultStyledDocument class (Table 22-25).

The base property reflects the base URL for relative hyperlink references. If you use the setPage( ) method of JEditorPane, this property is defined automatically from the HTML source. In other cases (such as manually reading an input stream), you may need to define this value yourself. The tokenThreshold property determines when page display begins. If you want some of your page to display as soon as possible, pick a relatively low value for this property. The default for Integer.MAX_VALUE is to wait for the entire document to load. The read-only styleSheet property gives you access to the stylesheet installed from the editor kit. You can change the initial stylesheet during the construction of this class, but you can also override individual styles defined in the current stylesheet at any time. The last property, preservesUnknownTags, determines whether non-HTML tags are kept in the document. If you turn off this feature, writing your document to an HTML file expunges unrecognized tags. (See the Javadoc for HTML.Tag for a list of recognized tags. The HTML class is covered next.)

23.6.1.2 Constructors
public HTMLDocument( )
public HTMLDocument(StyleSheet styles)
public HTMLDocument(AbstractDocument.Content c, StyleSheet styles)

Create new HTMLDocument objects. The first constructor uses the default stylesheet from the HTMLEditorKit. Alternatively, you can supply your own stylesheet, or your own content model and stylesheet, respectively. The content model allows you to supply your own variation on HTML content, but we recommend sticking with the default model.

23.6.1.3 Public content methods
public void setParagraphAttributes(int offset, int length, AttributeSet s, boolean replace)

Set the attribute(s) associated with the paragraph containing offset. If replace is false, s is merged with existing attributes. The length argument determines how many characters are affected by the new attributes. This is often the entire paragraph.

public void insertAfterEnd(Element elem, String htmlText) throws BadLocationException, IOException
public void insertAfterStart(Element elem, String htmlText) throws BadLocationException, IOException
public void insertBeforeEnd(Element elem, String htmlText) throws BadLocationException, IOException
public void insertBeforeStart(Element elem, String htmlText) throws BadLocationException, IOException

Insert htmlText at the respective point (after the end, before the start, etc.) relative to elem. Note that elem cannot be a leaf for the insertAfterStart( ) and insertBeforeEnd( ) methods.

public void setInnerHTML(Element elem, String htmlText) throws BadLocationException, IOException

Replace the children of elem with htmlText.

public void setOuterHTML(Element elem, String htmlText) throws BadLocationException, IOException

Replace elem in its parent with htmlText.

23.6.2 The HTML Class

HTMLEditorKit and HTMLDocument are by far the most important classes in the javax.swing.text.html package. If you are working on custom editors or browsers, you will become quite familiar with these classes. Beyond these, though, are several important supporting classes, one of which is the HTML class, a small helper class that is still integral to the use of HTMLEditorKit and HTMLDocument.

23.6.2.1 Inner classes

The HTML class defines three inner classes. Tags and attributes each have their own subclasses of these inner classes. We won't go into detail about these inner classes here. You can find that information in the HTML Editor Kit chapters on the book's web site.

public static class HTML.Attribute

Provide a template for creating a list of HTML attributes. Note that simply having an attribute in the list does not imply that it is supported by the HTMLEditorKit.

public static class HTML.Tag

Provide a type for creating a list of HTML tags. Note that simply having a tag in the list does not imply that it is supported by the HTMLEditorKit. For example, the <applet> tag is defined but not supported when displaying HTML documents.

public static class HTML.UnknownTag

This subclass of HTML.Tag allows the parser to produce valid entries for custom tags without modifying the parser. Any tag not recognized is created as an UnknownTag with a name corresponding to that used in the HTML document. For example, we could add <ora> tags to a document, and we would see them pass through the editor kit as UnknownTag objects. We have an example of using this class in the material on the web site, but if you are serious about custom tags, you should explore the XML tools available for Java, especially those included in SDK 1.4.

23.6.3 The StyleSheet Class

The last big piece of the HTML display puzzle is the StyleSheet class. This class defines the mechanisms for supporting cascading stylesheets. A stylesheet lists the formats available in a document along with the display characteristics of those formats. For example, it could dictate that all <p> paragraphs use 14-point Helvetica, all <h1> text use 28-point Helvetica, and all <h2> text use italicized 20-point Helvetica. This is, of course, an incomplete list, but you get the idea.

The Javadoc acknowledges that stylesheet support is incomplete in SDK 1.4. Each successive release of the swing.text.html package has included remarkable improvements. If you rely on this package for part of your application, you should make sure you have the latest possible version of Java. However, despite incomplete stylesheet support, you can still put it to use in your own applications. We look at an example of modifying the look of a standard HTML document through stylesheets at the end of this section.

23.6.3.1 Properties

The StyleSheet class defines a few properties, as shown in Table 23-13.

Table 23-13. StyleSheet properties

Property

Data Type

get

is

set

Default Value

base

URL

·

 

·

null

baseFontSize

int, String*

   

·

4

styleSheets

StyleSheet[]

·

   

null

*This property can be set as either an int or a String.

The baseFontSize property allows you to dictate the base font size for styles. The base size is used for normal <p> text, with larger fonts used for headers and smaller fonts used for sub- and superscripts. This font size is also the base for relative font sizes specified via <font> tags. The base property is the URL root for any relative URLs defined in the document. This property is normally set via the setPage( ) method of JEditorPane or the <base> header tag, but can be set manually if you are building a new document from scratch. You can use these two properties without creating a formal stylesheet. The styleSheets property returns an array of contained stylesheets. stylesheets can be arranged in a hierarchy to make construction and maintenance easier.

We have more detailed examples of altering HTML styles through the StyleSheet class in the chapter on the web site.



Java Swing
Graphic Java 2: Mastering the Jfc, By Geary, 3Rd Edition, Volume 2: Swing
ISBN: 0130796670
EAN: 2147483647
Year: 2001
Pages: 289
Authors: David Geary

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net