Tải bản đầy đủ - 0 (trang)
Chapter 23. Editor Panes and Editor Kits

Chapter 23. Editor Panes and Editor Kits

Tải bản đầy đủ - 0trang

This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks



I l@ve RuBoard



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 withEditorKit objects. AnEditorKit plugs into the editor pane to customize it for a

particular content type. Without an EditorKit telling it how to work, aJEditorPane 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



// HTMLExample.java

//

import javax.swing.*;

import javax.swing.event.*;

import java.io.*;



This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks



.



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);

}

}

[1]

We've created a minimal HTML browser. 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 byJEditorPane. The accessibleContext property depends on the type of



EditorKit in use. If anHTMLEditorKit is installed, a specialAccessibleJEditorPaneHTML object is used.

Otherwise, its superclass, AccessibleJEditorPane, is used. AccessibleJEditorPane extends the



This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks



.



JTextComponent.AccessibleJTextComponent class.



Table 23-1. JEditorPane properties

Property



Data type



get is set



Default value



AccessibleJEditorPane or

AccessibleJEditorPaneHTML



accessibleContexto



AccessibleContext



·



contentType



String



·



·



From editorKit



editorKitb



EditorKit



·



·



null



focusTraversalPolicy1.4, o



FocusTraversalPolicy



page



URL



·



scrollableTracksViewportWidtho



boolean



·



true



UIClassID o



String



·



"EditorPaneUI"



1.4



b



true



·

·



null



o



since 1.4, bound, overridden



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.

[2]

A custom FocusTraversalPolicy property is installed so the Tab key does not move focus to the next component.

The page property specifies the URL of the current page being displayed. ThescrollableTracksViewportWidth

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 aHyperlinkEvent, 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)



This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks



.



public synchronized HyperlinkListener[] getHyperlinkListeners( )

public void fireHyperlinkUpdate(HyperlinkEvent e)

JEditorPane objects also firePropertyChangeEvents 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 managingEditorKits. 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 appropriateEditorKit

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



This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks



.



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 ofDefaultEditorKit)



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 specifiedreference 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.

I l@ve RuBoard



This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks



I l@ve RuBoard



.



This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks

.



23.2 Overview of the Editor Kits

The following sections provide an overview of the various editor kits. With minor variations, this information applies to all editor

kits.



23.2.1 The EditorKit Class

The EditorKit class is the abstract base class for all editor kits. It has a number of methods that define the model (e.g.,



createDefaultDocument( )), the view (e.g., getViewFactory( )), the capabilities (getActions( )), and the I/O strategy (read(

) and write( )) for a given type of document content.Figure 23-2 shows the EditorKit class and the many classes and interfaces

it interacts with.



Figure 23-2. EditorKit class diagram



This figure shows several important things about the EditorKit class. First, each EditorKit instance is typically associated with

a single JEditorPane (though in some cases, it doesn't care). TheEditorKit defines how to create a defaultDocument as well

as how to read and write the Document to a stream. In addition, eachEditorKit may define a ViewFactory responsible for

creating View objects for each Element in the Document. Finally, the diagram shows that anEditorKit may define a set of



Actions that it supports.

The other classes shown in the diagram are the subclasses of EditorKit and AbstractAction. We'll look at each of these

classes, as well as some inner classes not shown on the diagram, throughout this chapter.



This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks

.



23.2.1.1 Properties



EditorKit defines the properties shown inTable 23-3. The actions property defines the set of actions that can be used on a text

component, which uses a model and a view produced by this EditorKit. contentType indicates the MIME type of the data that

this kit supports. The viewFactory property is the ViewFactory object used to createView objects for theElement s of the

document type produced by the kit. The accessors for all three of these properties are abstract.



Table 23-3. EditorKit properties

Property



Data type



get



is



set



Default value



actions



Action[]



·



Abstract



contentType



String



·



Abstract



viewFactory



ViewFactory



·



Abstract



23.2.1.2 Abstract methods



The following methods must be defined by implementations of this class:



public abstract Object clone( )

Return a copy of the editor kit. EditorKit implements Cloneable so that new instances can be created quickly.



public abstract Caret createCaret( )

Create a new Caret to be used with theJEditorPane. However, this method is currently not called anywhere within

Swing—Carets are initially installed via thecreateCaret( ) method in BasicTextUI and can be changed via a call to



setCaret( ) on any JTextComponent.



public abstract Document createDefaultDocument( )

Called by the BasicTextUI when installing a UI for a component and byJTextComponent before loading a new

document from a stream. It should return a new Document object of the appropriate type for the kit.Figure 23-3

shows how this method is called when a new JEditorPane is created without specifying a document.



Figure 23-3. Default document creation using EditorKit



This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks

.



public abstract void read(InputStream in, Document doc, int pos) throws IOException, BadLocationException

public abstract void read(Reader in, Document doc, int pos) throws IOException, BadLocationException

Populate the given Document, based on data read from the stream or reader. The data read is inserted at the

specified document position (use 0 if this is a new, empty document).



public abstract void write(OutputStream out, Document doc, int pos, int len) throws IOException, BadLocationException

public abstract void write(Writer out, Document doc, int pos, int len) throws IOException, BadLocationException

Write the specified portion of the document to the specified stream. To write the entire document, call write(aWriter,



aDoc, 0, aDoc.getLength( )).

These read( ) and write( ) methods support any arbitrary text format. For simple text, the data read and written is plain text;

more advanced editor kits might be able to read attribute and style information or well-defined markup languages like HTML or

XML.



23.2.1.3 Other methods



These methods are not abstract, but the default implementations do nothing:



public void install( JEditorPane c)

Called once the content type for the JEditorPane has been determined. It associates the kit with the editor pane.

Subclasses that need to query or listen to the editor pane for any reason should take advantage of this method.



public void deinstall( JEditorPane c)



This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks



Called when the JEditorPane changes its editor kit. For example, subclasses may take advantage of this method to

remove listeners from the pane.



23.2.2 The TextAction Class

Way back in Chapter 3, we introduced theAction interface and theAbstractAction default implementation. To quickly

review, Actions are a way to encapsulate some common piece of functionality, along with an associated name, icon, and other

attributes. Action extends the ActionListener interface, so any Action can be added as a listener to components that fire



Action events.

When working with any word processor or basic editor, you perform "actions" all the time. The simplest example occurs every

time you type a character. Some action is performed to add that character to the document and the display. More interesting

examples include making a segment of text bold, copying a selection of text, or changing the current font.

Swing provides support for many of these common activities through classes that extend the TextAction abstract class. The

specific actions available are defined as inner classes of the EditorKit subclasses. We'll cover each of these in the sections

that follow. In this section, we'll briefly cover the TextAction class itself, so you understand what all these new actions have in

common. Appendix B lists all the actions provided by Swing's standard components.

Note that if you want to define your own Action implementations that manipulate text components, they don't have to extend



TextAction. In most cases you'll want to because itsgetTextComponent( ) method makes it convenient to create a single

instance that can work with multiple text components.



23.2.2.1 Constructor



public TextAction(String name)

Pass the action name up to its superclass, where it is assigned to the Action.NAME property. Recall from the

discussion of Action that this property is typically the primary key used to identify actions.



23.2.2.2 Static method



public static final Action[] augmentList(Action[] list1, Action[] list2)

Add the actions in the second list to those in the first list. Any action names in both lists are mapped to the Action

specified in the second list. This method can be used by an EditorKit that adds new actions to the actions supported

by its superclass.



This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks

.



23.2.2.3 Protected methods



protected final JTextComponent getFocusedComponent( )

Return JTextComponent.getFocusedComponent( ).

protected final JTextComponent getTextComponent(ActionEvent e)

Determine the currently active text component, allowing actions to be shared by multiple text components. If the

given event has a JTextComponent as its target, that component is returned. If not, the result of



getFocusedComponent( ) is returned.



23.2.3 The DefaultEditorKit Class

DefaultEditorKit, a subclass of EditorKit, provides a great deal of default behavior applicable to most document types. As

we'll see, the most interesting features available in this class are provided by the actions it supports through its numerous inner

classes.

When used directly, DefaultEditorKit supports only plain-text data. Its actions deal with tasks such as copying and pasting

data, and its I/O methods read and write only plain text. However, the important thing about this class is that it can be extended

to add more features, and the actions it defines are still useful. We'll see extensions of DefaultEditorKit in the sections that

follow.



23.2.3.1 Properties



DefaultEditorKit defines values for the properties shown inTable 23-4. Each action is an instance of an inner class capable of

performing a given task. The contentType for editors using DefaultEditorKit is "text/plain", indicating that styled text is not

supported. The viewFactory property is set tonull, indicating that users of this class must provideViewFactory support via the

TextUI.



Table 23-4. DefaultEditorKit properties

Property



Data type



get is set



Default value



actions o



Action[]



·



Array of 53* TextAction objects



contentTypeo



String



·



"text/plain"



viewFactoryo



ViewFactory ·



o



overridden



*As of 1.4; there were 47 when Swing was first released.

See also properties from theEditorKit class (Table 23-3).



null



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 23. Editor Panes and Editor Kits

Tải bản đầy đủ ngay(0 tr)

×