19.2 The JTextComponent Class


The six concrete Swing text component classes have quite a bit in common. Consequently, they share a common base class, JTextComponent. Figure 19-2 shows the class hierarchy for the Swing text components. As you can see, the concrete text components are in the javax.swing package with the rest of the Swing component classes, but JTextComponent and all its supporting classes can be found in javax.swing.text.

Figure 19-2. The Swing text components
figs/swng2.1902.gif

JTextComponent is an abstract class that serves as the base class for all text-based Swing components. It defines a large number of properties and methods that apply to its subclasses. In this introductory chapter, we'll pass quickly over many of these properties, as they require an understanding of the underlying model and view aspects of the text framework.

19.2.1 Properties

JTextComponent defines the properties and default values shown in Table 19-1. document is a reference to the Document model for the component, where the component's content data is stored. (We'll discuss the details of the Document interface in Chapter 22.) The UI property for all text components is a subclass of javax.swing.plaf.TextUI.

Table 19-1. JTextComponent properties

Property

Data type

get

is

set

Default value

accessibleContexto

AccessibleContext

·

   

AccessibleJTextComponent

actions

Action[]

·

   

From the UI's EditorKit

caretb

Caret

·

 

·

null

caretColorb

Color

·

 

·

null

caretPosition

int

·

 

·

From caret

disabledTextColorb

Color

·

 

·

null

documentb

Document

·

 

·

null

dragEnabled1.4

boolean

·

 

·

false

editableb

boolean

 

·

·

true

focusAcceleratorb

char

·

 

·

'\0'

highlighterb

Highlighter

·

 

·

null

keymapb

Keymap

·

 

·

null

layouto

LayoutManager

·

 

·

null

marginb

Insets

·

 

·

From UI

navigationFilter1.4

NavigationFilter

·

 

·

null

preferredScrollableViewportSizeo

Dimension

·

   

Preferred size of component

scrollableTracksViewportHeighto

boolean

·

   

See below

scrollableTracksViewportWidtho

boolean

·

   

See below

selectedText

String

·

   

From document

selectedTextColorb

Color

·

 

·

null

selectionColorb

Color

·

 

·

null

selectionEnd

int

·

 

·

From caret

selectionStart

int

·

 

·

From caret

text

String

·

 

·

From document

UIb

TextUI

·

 

·

From L&F

1.4since 1.4, bbound, ooverridden

See also properties from the JComponent class (Table 3-6).

accessibleContext refers to an instance of the inner class AccessibleJTextComponent that implements the AccessibleText interface, which is described in Chapter 25.

The actions property specifies a list of Actions (such as page-up, change-font, or paste-from-clipboard) that are available to the component. The actual list is created by the component's EditorKit, which we'll cover in detail in Chapter 23. This read-only property exists for the convenience of the text component and those who subclass it, and the presence or absence of an Action on the list does not mean that Action is or is not installed in the component's active Keymap or InputMap.

caret represents the location at which data is inserted into the document (in other words, the cursor position; Swing uses the term caret instead of cursor). highlighter is an object responsible for drawing highlighted text. keymap allows you to specify, for example, the keystrokes that cause text to be cut (e.g., Ctrl-X) or pasted (e.g, Command-V). We'll discuss all three of these in Chapter 21.

caretColor , disabledTextColor, selectionColor , and selectedTextColor simply specify the color used to render the caret, disabled text, selection background, and selected text, respectively.[1]

[1] The regular text color is stored in the inherited foreground property.

The dragEnabled property, new in SDK 1.4, should be set to true to enable automatic drag handling (if the L&F supports it). Because automatic drag could possibly change the way text-selection gestures are interpreted, the default value for this property is false. Note that the accessor method is named getDragEnabled( ), not isDragEnabled( ), as convention would dictate.

The editable property indicates whether the document can be edited. If this property is set to false, characters typed into the component are not inserted the component is used only for displaying.

The focusAccelerator property specifies the key that can be used to give focus to the text component. The default value (\0) indicates that no focus accelerator has been set.

The inherited layout property defaults to null because the layout of text components is handled by the View hierarchy (more on this later). The margin property specifies the distance between the component's text and its border (using an instance of java.awt.Insets).

navigationFilter (if not null) is used by the caret to restrict cursor movement.

The selectedText and text properties are managed by the component's Document while selectionStart, selectionEnd, and caretPosition delegate to the caret.

The preferredScrollableViewportSize property (from the Scrollable interface) simply delegates to getPreferredSize( ). The values of the other two properties from the Scrollable interface, scrollableTracksViewportHeight and scrollableTracksViewport-Width, are determined by the size of the JViewport containing the component. If the viewport is larger than the preferred size of the component, these properties are true. Otherwise (or if the component's parent is not a JViewport), they are false.

19.2.2 Events

JTextComponent fires a CaretEvent any time the state of the component's Caret changes. So any time the cursor position changes, an event is fired. The only exception is that while a selection is being made (the mouse is being dragged), events are not fired as the cursor moves, only when the mouse is released and the selection has been created.

The following standard methods are provided for working with caret events. (Note that the getCaretListeners( ) method was introduced in SDK 1.4.)

public void addCaretListener(CaretListener listener)
public void removeCaretListener(CaretListener listener)
public CaretListener[] getCaretListeners( )

The CaretEvent class and CaretListener interface are described in detail in Chapter 21.

In addition to firing CaretEvents, JTextComponents naturally fire property change events when the values of bound properties are changed.

19.2.3 Constants

Table 19-2 defines the JTextComponent constants. There are no constants defined for any bound properties other than focusAccelerator, but there is nothing special about FOCUS_ACCELERATOR_KEY, and its solitary existence as a constant is most likely evidence of an oversight with respect to the other bound properties.

Table 19-2. JTextComponent constants

Constant

Type

Description

DEFAULT_KEYMAP

String

The name of the default keymap used by all text components. This string can be used as a parameter to the static getKeymap( ) method.

FOCUS_ACCELERATOR_KEY

String

The bound property name for the focus accelerator, used when firing property change events.

19.2.4 Constructor

public JTextComponent( )

Create a new editable component and update the UI (causing many of the null properties listed in Table 19-1 to be set).

19.2.5 Clipboard Methods

These methods allow you to move data to and from the system clipboard:

public void copy( )

Copy the currently selected range in the component's model to the system clipboard. No change is made to the document itself.

public void cut( )

Copy the currently selected range in the component's model to the system clipboard. The selected range (if any) is removed from the document.

public void paste( )

Copy the contents of the system clipboard into the document. If there is an active selection, it is replaced by the pasted contents. If there is no selection, the contents are inserted in front of the current insert position (caret).

19.2.6 Selection Methods

These methods are concerned with selecting (highlighting) text:

public void moveCaretPosition(int pos)

Form a selection by moving the caret to the specified position. The selection begins at the location specified when setCaretPosition( ) was last called. It throws an IllegalArgumentException if pos is not between 0 and getText( ).length( ).

public void replaceSelection(String content)

Replace the currently selected area with content. If there is no current selection, the input text is inserted at the current caret position.

public void select(int selectionStart, int selectionEnd)

Select an area of the document bounded by the input offsets. This method is implemented by calling setCaretPosition( ) and moveCaretPosition( ), but it does not throw an exception even if selectionStart or selectionEnd is out of bounds. According to the documentation for JTextComponent, setCaretPosition( ) and moveCaretPosition( ) should be called directly instead of calling select( ), which is provided only for backward compatibility.

public void selectAll( )

Select all the text in the component.

19.2.7 View Methods

These methods provide mappings between model and view coordinate systems (e.g., pixel (53,71) of the view might correspond to character 42 of the document). They also provide information necessary for scrolling the text component.

public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction)
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction)

Return the "unit" and "block" scroll increments (in pixels) desired by the component. The default implementation returns 10% and 100% of the size of the visible area, respectively. Subclasses are expected to compute a scroll increment that exposes some logical portion of the display, such as a row or column of data. The input Rectangle defines the size of the current view area. The orientation must be either SwingConstants.VERTICAL or SwingConstants.HORIZONTAL. The direction indicates which direction to scroll. Negative values indicate a scroll up or left; positive values indicate down or right. For more information on scrolling, see Section 11.2.5.

public Rectangle modelToView(int pos) throws BadLocationException

Convert the input position to an area in the view coordinate system. pos is an offset into the content of the text component.

public int viewToModel(Point pt)

Return the offset of the character found at the location described by pt.

19.2.8 Working with Keymaps

The Swing text components allow you to map keystrokes to specified actions. This capability existed before the more flexible and universal InputMap and ActionMap mechanisms emerged. (These are discussed in Section 3.5.14.) The Keymap-based methods are still available for backward compatibility and were reimplemented using the new framework. The following methods are defined in the JTextComponent base class and are discussed in more detail in Chapter 21:

public static Keymap addKeymap(String name, Keymap parent)

Create a new Keymap with the specified parent. If the input map name is not null, the new Keymap is added to an internal table using the map name.

public static Keymap getKeymap(String name)

Return the Keymap associated with the given name.

public static Keymap removeKeymap(String name)

Remove (and return) the Keymap specified by the input map name.

public static void loadKeymap(Keymap map, JTextComponent.KeyBinding[] bindings, Action[] actions)

This static utility method can be used to insert Action bindings into a Keymap.

19.2.9 Other Methods

public String getText(int offset, int len) throws BadLocationException

Return a portion of the text starting at the input offset (the distance, in characters, from the beginning of the document) containing the requested number of characters.

public void write(Writer out) throws IOException

Write the contents of the document to the given Writer. The default implementation stores the document as plain text, but subclasses may produce alternate data formats, such as HTML.

public void read(Reader in, Object desc) throws IOException

Set the contents of the component from a Reader. The default implementation reads plain text, but subclasses may handle more complex formats, such as HTML. The second parameter is intended to describe the stream and may be null. If it's not, it is added as a property of the document; HTML documents and the JEditorKit use URLs as descriptions to help resolve relative hyperlinks.

public void updateUI( )

This method is called to indicate that the L&F has changed.



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