23.1 The JEditorPane Class


JEditorPane is an extension of JTextComponent capable of displaying various types of content, such as HTML and RTF. It is not intended to be used as a full-featured web browser, but it can be used to view simple HTML and is ideal for integrating online help into Java applications.

JEditorPanes work closely with EditorKit objects. An EditorKit plugs into the editor pane to customize it for a particular content type. Without an EditorKit telling it how to work, a JEditorPane can't function. We discuss EditorKit in the next section.

Figure 23-1 shows the JEditorPane in action, displaying a portion of the Javadoc for the JEditorPane class. Here's the code:

Figure 23-1. JEditorPane showing an HTML page
figs/swng2.2301.gif
// HTMLExample.java // import javax.swing.*; import javax.swing.event.*; import java.io.*; public class HTMLExample {   public static void main(String[] args) {     JEditorPane pane = null;     try {       pane = new JEditorPane(args[0]);     }     catch (IOException ex) {       ex.printStackTrace(System.err);       System.exit(1);     }     pane.setEditable(false);     // Add a hyperlink listener.     final JEditorPane finalPane = pane;     pane.addHyperlinkListener(new HyperlinkListener( ) {       public void hyperlinkUpdate(HyperlinkEvent ev) {         try {           if (ev.getEventType( ) == HyperlinkEvent.EventType.ACTIVATED)             finalPane.setPage(ev.getURL( ));         } catch (IOException ex) { ex.printStackTrace(System.err); }       }     });     JFrame frame = new JFrame( );     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     frame.setContentPane(new JScrollPane(pane));     frame.setSize(350,400);     frame.setVisible(true);   } } 

We've created a minimal HTML browser.[1] In a real application, you'd want to do things like change the cursor while new pages are being loaded and handle exceptions more elegantly. The anonymous inner class in this example shows a quick way to enable hyperlinks when viewing text in a JEditorPane. We'll look at the classes and methods used here in the next few sections.

[1] This simple browser will not handle all HTML pages. Swing is still being enhanced to provide better HTML support. However, significant progress has been made since earlier releases.

23.1.1 Properties

Table 23-1 shows the properties defined by JEditorPane. The accessibleContext property depends on the type of EditorKit in use. If an HTMLEditorKit is installed, a special AccessibleJEditorPaneHTML object is used. Otherwise, its superclass, AccessibleJEditorPane, is used. AccessibleJEditorPane extends the JTextComponent.AccessibleJTextComponent class.

Table 23-1. JEditorPane properties

Property

Data type

get

is

set

Default value

accessibleContexto

AccessibleContext

·

   

AccessibleJEditorPane or AccessibleJEditorPaneHTML

contentType

String

·

 

·

From editorKit

editorKitb

EditorKit

·

 

·

null

focusTraversalPolicy1.4, o

FocusTraversalPolicy

 

·

 

true

page

URL

·

 

·

null

scrollableTracksViewportWidtho

boolean

·

   

true

UIClassIDo

String

·

   

"EditorPaneUI"

1.4since 1.4, bbound, ooverridden

See also properties from the JTextComponent class (Table 19-1).

The contentType property reflects the type of content displayed by the editor. This value is taken from the installed EditorKit and typically has values such as "text/plain", "text/html", and "text/rtf". The editorKit supplies everything needed to work with a particular content type.

A custom FocusTraversalPolicy property is installed so the Tab key does not move focus to the next component.[2] The page property specifies the URL of the current page being displayed. The scrollableTracksViewportWidth property is true for this class.

[2] In previous versions this was implemented using the (now deprecated) managingFocus property.

23.1.2 Events

JEditorPane s fire a special type of event called a HyperlinkEvent, which is typically fired when the user clicks on a hyperlink; the program normally responds by loading a new page. To support this event type, a corresponding event class and listener interface are available in the javax.swing.event package. These are described briefly at the end of this section.

As you'd expect, the following methods are provided for working with these events:

public synchronized void addHyperlinkListener(HyperlinkListener listener)
public synchronized void removeHyperlinkListener(HyperlinkListener
listener)
public synchronized HyperlinkListener[] getHyperlinkListeners( )
public void fireHyperlinkUpdate(HyperlinkEvent e)

JEditorPane objects also fire PropertyChangeEvents when the editorKit property is changed. getHyperlinkListeners( ) was introduced in SDK 1.4. While not restricted to HTML documents by any means, HTML is a natural and familiar environment for hyperlinks (so we have chosen to detail them in Section 23.3 later in this chapter).

23.1.3 Constructors

The following constructors are provided. Note that the last two may throw an IOException if they are unable to load the specified URL (including if the server returns an HTTP error).

public JEditorPane( )

Create an empty pane.

public JEditorPane(String url) throws IOException
public JEditorPane(URL initialPage) throws IOException

Create a pane displaying the specified URL. contentType and editorKit are set based on the content type of the URLConnection created from the given URL. Because these constructors attempt to open a URL, they may throw an IOException if the URL cannot be found.

23.1.4 EditorKit Methods

The following methods are available for managing EditorKits. You won't need to use any of these methods unless you're defining your own EditorKits for working with various content types.

public EditorKit getEditorKitForContentType(String type)

Return an EditorKit for the given content type. An attempt is made to create the appropriate EditorKit if one has not already been set (via a call to setEditorKitForContentType( )). If the appropriate EditorKit cannot be created, a DefaultEditorKit is returned.

public void setEditorKitForContentType(String type, EditorKit k)

Explicitly set the EditorKit to be used for a given content type.

public static EditorKit createEditorKitForContentType(String type)

Attempt to create a new EditorKit instance for the given content type. In order for this method to return a non-null object, the content type must be associated with an editor kit class name via registerEditorKitForContentType( ).

public static void registerEditorKitForContentType(String type, String classname)

Called to associate a content type with an editor kit class name. It is called four times in the JEditorPane initializer block. These calls define the mappings shown in Table 23-2.

Table 23-2. Default content type mappings

Content type

Class

application/rtf

javax.swing.text.rtf.RTFEditorKit

text/html

javax.swing.text.html.HTMLEditorKit

text/plain

javax.swing.JEditorPane.PlainEditorKit (a package-private subclass of DefaultEditorKit)

text/rtf

javax.swing.text.rtf.RTFEditorKit

public static String getEditorKitClassNameForContentType(String type)

Return the class name associated with the specified content type (introduced in SDK 1.3).

23.1.5 Miscellaneous Methods

public void setPage(String url) throws IOException

A convenience method used to set the current page, given a URL string. An IOException is thrown if the given URL cannot be loaded.

public void scrollToReference(String reference)

Used by setPage( ) to scroll the display to the specified reference within the current document. This method provides support for URLs containing named anchors, like events.html#february. Note that this method works only with HTML documents. It was protected prior to SDK 1.4 but is now available to everyone.



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