22.1 The JTextPane Class


JTextPane is a multiline text component that can display text with multiple fonts, colors, and even embedded images. It supports named hierarchical text styles and has other features that can help implement a word processor or a similar application.

Technically, JTextPane is a subclass of JEditorPane, but it usually makes more sense to think of JTextPane as a text component in its own right. JEditorPane uses "editor kits" to handle text in various formats (such as HTML or RTF) in a modular way. Use a JEditorPane when you want to view or edit text in one of these formats. Use a JTextPane when you want to handle the text yourself. We'll cover JEditorPane and editor kits (including JTextPane's editor kit, StyledEditorKit) in Chapter 23.

22.1.1 Properties

JTextPane defines the properties shown in Table 22-1. document and styledDocument are both names for the same property. The model returned by getDocument( ) always implements StyledDocument (which is an interface that extends Document). Attempting to call setDocument( ) with a Document that is not a StyledDocument throws an IllegalArgumentException. (The Document and StyledDocument interfaces are described in detail later in this chapter.)

Table 22-1. JTextPane properties

Property

Data type

get

is

set

Default value

characterAttributes

AttributeSet

·

     

documento

Document

·

 

·

Value of styledDocument

editorKitb, o

EditorKit

·

 

·

StyledEditorKit

inputAttributes

MutableAttributeSet

·

     

logicalStyle

Style

·

 

·

 

paragraphAttributes

AttributeSet

·

     

styledDocument

StyledDocument

·

 

·

DefaultStyledDocument

UIClassIDo

String

·

   

"TextPaneUI"

bbound, ooverridden

See also properties from the JTextComponent class (Table 19-1) and the JEditorPane class (Table 23-1). (Not shown are the contentType, page, and accessibleContext properties, inherited from JEditorPane.)

The inputAttributes, characterAttributes , paragraphAttributes, and logicalStyle properties are not properties of the JTextPane itself, but of the text under the caret. The types of these properties are related: the Style interface extends the MutableAttributeSet interface, which extends the AttributeSet interface. (We'll tackle these interfaces in Section 22.2 later in this chapter.) The values of these properties are stored by the pane's styledDocument[1] and typically change as the position of the caret moves. Because of this (and also because the setCharacterAttributes( ) and setParagraphAttributes( ) methods require an extra boolean parameter, which makes them invalid as JavaBeans property mutators), we elaborate on these methods later in this chapter in Section 22.1.3.

[1] Actually, inputAttributes is maintained by the pane's editorKit, which is a CaretListener of the Document. This read-only property is used by JTextPane when text is inserted. The newly inserted text will have the same attributes as the text immediately preceding it.

The editorKit property is inherited from JEditorPane, but there is little or no reason to deal with it directly. The editorKit defaults to an instance of StyledEditorKit. Attempting to set an editor kit that is not a StyledEditorKit (or a subclass) throws an IllegalArgumentException.

22.1.2 Constructors

public JTextPane( )

Create an empty text pane.

public JTextPane(StyledDocument doc)

Create a text pane displaying the specified document.

22.1.3 Attribute and Style Methods

These methods manipulate the character attributes, paragraph attributes, and logical styles of the pane's document. Character attributes include font and text color. Paragraph attributes can also include paragraph indentation and spacing. Styles are groups of attributes that can be reused throughout the document. Named styles are styles that have been assigned a name. The document keeps track of these styles so you can look them up and reuse or modify them later. Changing the attributes of a style changes all text that is tagged with that style.

You can apply logical styles to whole paragraphs. Logical styles define a baseline set of attributes that can be overridden by local paragraph or character attributes. (See the discussion in Section 22.3.5 later in this chapter for more details.) When setting the logical style for a paragraph, you can use a named style to facilitate reuse. We do this in the example editor later in the chapter, presenting a menu of the named styles.

Rather than operating on one attribute at a time, the attribute and style methods operate on collections of attributes held in objects implementing AttributeSet, MutableAttributeSet, or Style.

The accessor methods may return null if there is no content at the caret position or if there are no attributes to return. The mutator methods are thread-safe, so (unlike most Swing methods) they can be called safely by threads other than the event-dispatching thread.

public AttributeSet getCharacterAttributes( )

Return the character attributes that apply to the text at the caret position. Only the current caret position is used; any selected text is ignored.

public MutableAttributeSet getInputAttributes( )

This method delegates to the pane's editorKit (by calling its method of the same name). The effect is identical to calling getCharacterAttributes( ), except the result is mutable. One way to change how inserted text appears in the pane is to manipulate the MutableAttributeSet returned by this method, but it is often easier to call setCharacterAttributes( ) instead.

public void setCharacterAttributes(AttributeSet attr, boolean replace)

Apply the specified attributes to the selected characters. Even if there is no selection, the attributes apply (by updating inputAttributes) to any new text inserted at the current caret location. If you want the new set of attributes to completely replace the existing set (instead of augmenting it), use true for the replace argument.

public AttributeSet getParagraphAttributes( )

Return the paragraph attributes for the text at the caret position. Only the current caret position is used; any selected text is ignored.

public void setParagraphAttributes(AttributeSet attr, boolean replace)

Apply the supplied attributes to any selected (or partially selected) paragraphs. If there is no selection, the attributes are applied to the paragraph at the current caret position. If you want the new set of attributes to completely replace the existing set (instead of augmenting it), use true for the replace argument.

public Style getLogicalStyle( )

Return the Style that applies to the paragraph containing the caret. Any selected text is ignored.

public void setLogicalStyle(Style s)

Set the Style for the paragraph containing the caret. Any selected text is ignored.

22.1.4 Insertion/Replacement Methods

In addition to displaying text, JTextPane can display Icons and arbitrary Components. This flexibility makes it possible to display documents with embedded images or interactive documents such as HTML forms.

There are three insertion methods: one inserts text, one inserts an Icon, and one inserts a Component. Despite their dissimilar names, all three work the same way. The new insertion replaces the current selection or, if there is no selection, appears at the current caret position. (If you want to insert at a position other than the caret position, you can do so by manipulating the pane's document directly.) If you want to insert without replacing the current selection, you need to "deselect" before calling one of these methods. Here's one way to do this:

pane.getCaret( ).setDot(pane.getCaretPosition( ));

These methods are thread-safe, so (unlike most Swing methods) they can be called safely by threads other than the event-dispatching thread.

public void replaceSelection(String content)

Insert the specified text into the document, replacing anything currently selected. If content is null, it deletes the current selection. Any new text uses the attributes specified by the inputAttributes property.

public void insertIcon(Icon c)

Insert an Icon into the document, replacing anything currently selected.

public void insertComponent(Component c)

Insert a Component into the document,[2] replacing the current selection. The component is laid out relative to the text baseline, according to its alignmentY property (see Table 3-6). If c is a JComponent, calling c.setAlignmentY(0.8) places 80% of the component above the baseline.

[2] Note that while it is usually fine for multiple JTextPanes to share the same Document, it can be a problem if you plan to use this method because it is forbidden to add a Component to more than one Container.

Here's a short example showing how these methods work. We create a JTextPane with three buttons that insert a text string, button, and icon. Figure 22-1 shows it after it's been played with a bit.

// PaneInsertionMethods.java // import javax.swing.*; import java.awt.BorderLayout; import java.awt.event.*; // Show how icons, components, and text can be added to a JTextPane. public class PaneInsertionMethods {   public static void main(String[] args) {     final JTextPane pane = new JTextPane( );     // Button to insert some text     JButton textButton = new JButton("Insert Text");     textButton.addActionListener(new ActionListener( ) {       public void actionPerformed(ActionEvent event) {         pane.replaceSelection("text");       }     });     // Button to insert an icon     final ImageIcon icon = new ImageIcon("bluepaw.gif");     JButton iconButton = new JButton(icon);     iconButton.addActionListener(new ActionListener( ) {       public void actionPerformed(ActionEvent event) {         pane.insertIcon(icon);       }     });     // Button to insert a button     JButton buttonButton = new JButton("Insert Button");     buttonButton.addActionListener(new ActionListener( ) {       public void actionPerformed(ActionEvent event) {         pane.insertComponent(new JButton("Click Me"));       }     });     // Layout     JPanel buttons = new JPanel( );     buttons.add(textButton);     buttons.add(iconButton);     buttons.add(buttonButton);     JFrame frame = new JFrame( );     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);      frame.getContentPane( ).add(pane, BorderLayout.CENTER);     frame.getContentPane( ).add(buttons, BorderLayout.SOUTH);     frame.setSize(360,180);     frame.setVisible(true);   } } 
Figure 22-1. JTextPane containing JButtons and ImageIcons
figs/swng2.2201.gif

22.1.5 Named Style Methods

JTextPane provides three methods for dealing with named styles, but it doesn't manage the styles itself, delegating this to its document instead. See the similarly named methods in the StyledDocument interface, the DefaultStyledDocument class, and the StyleContext class (later in this chapter) for more details on named styles.

public Style getStyle(String name)

Return a named Style previously added to this document.

public void removeStyle(String name)

Remove a named Style from this document. (It may also be removed from other StyledDocuments that share the same set of Styles.)

public Style addStyle(String name, Style parent)

Create and return a new, empty Style and add it to the document's style hierarchy. The name of the new style is name, which may be null if you want to create an unnamed style.[3] The parent parameter (if not null) is the Style used to resolve attributes not found in the new Style.

[3] Unnamed styles can be used but can't be accessed by the getStyle( ) and removeStyle( ) methods.

This method is poorly named. It doesn't "add" anything to its Style argument, but rather creates a new Style with the supplied name and parent.



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