Using Text Components

 < Day Day Up > 

Using Text Components

This section gives background information you might need when using Swing's text components. If you intend to use an unstyled text componenta text field, password field, formatted text field, or text areawe recommend that you go to its how-to section in Chapter 7 and return here only if necessary. If you intend to use a styled text component, then you're welcome to go to Chapter 7's How to Use Editor Panes and Text Panes (page 200), but you'll probably need to read this section as well. If you don't know which component you need, read on.

Swing's text components display text and optionally allow the user to edit the text. Programs need text components for tasks ranging from the straightforward (enter a word and press Enter) to the complex (display and edit styled text with embedded images in an Asian language).

Swing provides six text components, along with supporting classes and interfaces, that meet even the most complex text requirements. In spite of their different uses and capabilities, all of Swing's text components inherit from the same superclass, JTextComponent , [12] which provides a highly configurable and powerful foundation for text manipulation.

[12] JTextComponent API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/text/JTextComponent.html.

Figure 14 shows the JTextComponent hierarchy.

Figure 14. The JTextComponent hierarchy.

graphics/03fig14.gif

Figure 15 shows an application called TextSamplerDemo that uses one of each of Swing's text components.

Figure 15. A screenshot of the TextSamplerDemo .

graphics/03fig15.jpg

Try This:

  1. graphics/cd_icon.gif

    Run TextSamplerDemo using Java Web Start or compile and run the example yourself. [13]

    [13] To run TextSamplerDemo using Java Web Start, click the TextSamplerDemo link on the RunExamples/components.html page on the CD. You can find the source files here: JavaTutorial/uiswing/components/example-1dot4/index.html#TextSamplerDemo .

  2. Type some text into the text field and press Enter. Do the same with the password field. The label beneath the fields is updated when you press Enter.

  3. Try entering valid and invalid dates into the formatted text field. Note that when you press Enter the label beneath is updated only if the date is valid.

  4. Select and edit text in the text area and the text pane. Use special keyboard keys to cut, copy, and paste text.

  5. Try to edit the text in the editor pane, which has been made uneditable with a call to setEditable .

  6. Look in the text pane to find an example of an embedded component and an embedded icon.

TextSamplerDemo uses the text components in very basic ways. Table 9 tells you a bit more about what you can do with each kind of text component.

Table 9. Kinds of Text Components

Group

Description

Swing Classes

Text Controls

Also known simply as text fields, text controls can display and edit only one line of text. Like buttons , they generate action events. Use them to get a small amount of textual information from the user and take some action after the text entry is complete.

JTextField and its subclasses JPasswordField and JFormattedTextField

Plain Text Areas

JTextArea can display and edit multiple lines of text. Although a text area can display text in any font, all of the text is in the same font. Use a text area to allow the user to enter unformatted text of any length or to display unformatted help information.

JTextArea

Styled Text Areas

A styled text component can display and edit text using more than one font. Some styled text components allow embedded images and even embedded components. Styled text components are powerful and multi- faceted components suitable for high-end needs, and offer more avenues for customization than the other text components. Because they are so powerful and flexible, styled text components typically require more up-front programming to set up and use. One exception is that editor panes can be easily loaded with formatted text from a URL, which makes them useful for displaying uneditable help information.

JEditorPane and its subclass JTextPane

Note: This book gives you information about the foundation laid by JTextComponent and tells you how to accomplish some common text- related tasks. Because JTextComponent and its subclasses have too many features to be completely described here, please periodically search the online newsletter, The Swing Connection , for pointers to more information: http://java.sun.com/products/jfc/tsc/index.html. We've also included The Swing Connection on the CD at: Docs/swingConnect/swingconnection.pdf .


Text Component Features

JTextComponent is the foundation for Swing's text components, and provides these customizable features for all of its descendants:

  • A model, known as a document , to manage the component's content.

  • A view, which is in charge of displaying the component on screen.

  • A controller, known as an editor kit , that can read and write text and that implements editing capabilitie.

  • Support for infinite undo and redo.

  • Pluggable caret and support for caret change listeners and navigation filters.

This section uses the application shown in Figure 16 to explore these capabilities. Although the demo application contains a customized instance of JTextPane , the capabilities discussed in this section are inherited by all of JTextComponent 's subclasses.

Figure 16. The TextComponentDemo application.

graphics/03fig16.gif

The upper text component is the customized text pane. The lower text component is an instance of JTextArea , which serves as a log that reports all changes made to the contents of the text pane. The status line at the bottom of the window reports either the location of the selection or the position of the caret, depending on whether text is selected.

Try This:

  1. graphics/cd_icon.gif

    Run TextComponentDemo using Java Web Start or compile and run the example yourself. [14]

    [14] To run TextComponentDemo using Java Web Start, click the TextSamplerDemo link on the RunExamples/components.html page on the CD. You can find the source files here: JavaTutorial/uiswing/components/example-1dot4/index.html#TextComponentDemo .

  2. Use the mouse to select text and place the cursor in the text pane. Information about the selection and cursor is displayed at the bottom of the window.

  3. Enter text by typing at the keyboard. You can move the caret around using four emacs key bindings: CTRL-B (backward one character), CTRL-F (forward one character), CTRL-N (down one line), and CTRL-P (up one line).

  4. Bring up the Edit menu, and use its various menu items to perform editing on the text in the text pane. Make a selection in the text area at the bottom of the window. Because the text area is uneditable, only some of the Edit menu's commands, such as copy-to-clipboard , work. It's important to note, though, that the menu operates on both text components.

  5. Use the items in the Style menu to apply different styles to the text in the text pane.

Associating Text Actions with Menus and Buttons

All Swing text components support standard editing commands such as cut, copy, paste, and inserting characters . Each editing command is represented and implemented by an Action object. (You can learn about actions by reading How to Use Actions (page 513) in Chapter 9.) Actions make it easy for you to associate a command with a GUI component, such as a menu item or button, and therefore build a GUI around a text component.

You can invoke the getActions method on any text component to get an array containing all of the actions it supports. Often it's convenient to load the array of actions into a HashMap so that your program can retrieve an action by name . Here's the code from TextComponentDemo that gets the actions from the text pane and loads them into a HashMap :

 private void createActionTable(JTextComponent textComponent) {     actions = new HashMap();     Action[] actionsArray = textComponent.getActions();     for (int i = 0; i < actionsArray.length; i++) {         Action a = actionsArray[i];         actions.put(a.getValue(Action.NAME), a);     } } 

Here's a convenient method for retrieving an action by its name from the HashMap :

 private Action getActionByName(String name) {     return (Action)(actions.get(name)); } 

You can use both methods verbatim in your programs.

Now let's look at how the Cut menu item is created and associated with the action of removing text from the text component:

 protected JMenu createEditMenu() {     JMenu menu = new JMenu("Edit");     ...     menu.add(getActionByName(DefaultEditorKit.cutAction));     ... 

This code gets the action by name using the handy method shown previously. It then adds the action to the menu. That's all you need to do. The menu and the action take care of everything else. You'll note that the name of the action comes from DefaultEditorKit . [15] This kit provides actions for basic text editing and is the superclass for all of the editor kits provided by Swing. So its capabilities are available to all text components unless overridden by a customization.

[15] DefaultEditorKit API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/text/DefaultEditorKit.html.

For efficiency, text components share actions. The Action object returned by getActionByName(DefaultEditorKit.cutAction) is shared by the uneditable JTextArea at the bottom of the window. This has two important ramifications :

  • Generally speaking, you shouldn't modify Action objects you get from editor kits. If you do, the changes affect all text components in your program.

  • Action objects can operate on other text components in the program, perhaps more than you intended. In this example, even though it's uneditable, the JTextArea shares actions with the JTextPane . (Select some text in the text area, then choose the cut-to-clipboard menu item. You'll hear a beep because the text area is uneditable.) If you don't want to share, consider instantiating the Action object yourself. DefaultEditorKit defines a number of useful Action subclasses.

Here's the code that creates the Style menu and puts the Bold menu item in it:

 protected JMenu createStyleMenu() {     JMenu menu = new JMenu("Style");     Action action = new StyledEditorKit.BoldAction();     action.putValue(Action.NAME, "Bold");     menu.add(action);     ... 

The StyledEditorKit provides Action subclasses to implement editing commands for styled text. You'll note that instead of getting the action from the editor kit, this code creates an instance of the BoldAction class. Thus, this action is not shared with any other text component, and changing its name won't affect any other text component.

Associating Text Actions with Keystrokes

In addition to associating an action with a GUI component, you can also associate an action with a keystroke, using a text component's input map. Input maps are described in How to Use Key Bindings (page 623) in Chapter 9.

The text pane in the TextComponentDemo supports four key bindings not provided by default.

  • CTRL-B for moving the caret backward one character

  • CTRL-F for moving the caret forward one character

  • CTRL-N for moving the caret down one line

  • CTRL-P for moving the caret up one line

The following code adds the CTRL-B key binding to the text pane. The code for adding the other three is similar.

 InputMap inputMap = textPane.getInputMap(); KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_B, Event.CTRL_MASK); inputMap.put(key, DefaultEditorKit.backwardAction); 

The code starts off by getting the text component's input map. Next , it gets a KeyStroke [16] object representing the CTRL-B key sequence. Finally, the code binds the key-stroke to the Action that moves the cursor backward.

[16] KeyStroke API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/KeyStroke.html.

Version Note: Before v1.3, you needed to use a JTextComponent feature called a keymap to associate keystrokes with actions. The keymap API still exists and works, but it is now implemented in terms of the key binding infrastructure added in v1.3. Here's the pre-v1.3 equivalent of the preceding code:

 //PRE-1.3 CODE Keymap keymap = textPane.addKeymap("MyEmacsBindings", textPane.getKeymap()); Action action = getActionByName(DefaultEditorKit.backwardAction); KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_B, Event.CTRL_MASK); keymap.addActionForKeyStroke(key, action); ... textPane.setKeymap(keymap); 

Implementing Undo and Redo

Implementing undo and redo has two parts :

  • Remembering undoable edits.

  • Implementing the undo and redo commands and providing a user interface for them.

Part 1: Remembering Undoable Edits

To support undo and redo, a text component must remember each edit that occurs, the order of edits, and what it takes to undo each edit. The example program uses an instance of the UndoManager [17] class to manage its list of undoable edits. The undo manager is created where the member variables are declared:

[17] UndoManager API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/undo/UndoManager.html.

 protected UndoManager undo = new UndoManager(); 

Now, let's look at how the program finds out about undoable edits and adds them to the undo manager.

A document notifies interested listeners whenever an undoable edit occurs on its content. An important step in implementing undo and redo is to register an undoable edit listener on the document of the text component. The following code adds an instance of MyUndoableEditListener to the text pane's document:

 lsd.addUndoableEditListener(new MyUndoableEditListener()); 

The undoable edit listener used in our example adds the edit to the undo manager's list:

 protected class MyUndoableEditListener implements UndoableEditListener {     public void undoableEditHappened(UndoableEditEvent e) {         //Remember the edit and update the menus         undo.addEdit(e.getEdit());         undoAction.updateUndoState();         redoAction.updateRedoState();     } } 

Note that this method updates two objects: undoAction and redoAction . These are the action objects attached to the Undo and Redo menu items, respectively. The next step shows you how the menu items are created and the implementation of the two actions. For general information about undoable edit listeners and undoable edit events, see How to Write an Undoable Edit Listener (page 721) in Chapter 10.

Note: By default, undoable edits can be as fine-grained as single key presses. It is possible, with some effort, to group edits so that (for example) a series of key presses is combined into one undoable edit. The implementation would require defining a class that intercepts undoable edit events from the document, combining them if appropriate and forwarding the results to your undoable edit listener.


Part 2: Implementing the Undo and Redo Commands

The first step in this part of implementing undo and redo is to create the actions to put in the Edit menu.

 JMenu menu = new JMenu("Edit"); //Undo and redo are actions of our own creation undoAction = new UndoAction(); menu.add(undoAction); redoAction = new RedoAction(); menu.add(redoAction); ... 

The undo and redo actions are implemented by custom AbstractAction subclasses: UndoAction and RedoAction , respectively. These classes are inner classes of the example's primary class.

When the user invokes the Undo command, UndoAction 's actionPerformed method, shown here, gets called:

 public void actionPerformed(ActionEvent e) {     try {         undo.undo();     } catch (CannotUndoException ex) {         System.out.println("Unable to undo: " + ex);         ex.printStackTrace();     }     updateUndoState();     redoAction.updateRedoState(); } 

This method calls the undo manager's undo method and updates the menu items to reflect the new undo/redo state. Similarly, when the user invokes the Redo command, the actionPerformed method in RedoAction gets called:

 public void actionPerformed(ActionEvent e) {     try {         undo.redo();     } catch (CannotRedoException ex) {         System.out.println("Unable to redo: " + ex);         ex.printStackTrace();     }     updateRedoState();     undoAction.updateUndoState(); } 

This method is similar except that it calls the undo manager's redo method.

Much of the code in the UndoAction and RedoAction classes is dedicated to enabling and disabling the actions as appropriate for the current state, and changing the names of the menu items to reflect the edit to be undone or redone.

Note: The implementation of undo and redo in TextComponentDemo was taken from the NotePad demo that comes with the Java 2 SDK. Many programmers will also be able to copy this implementation of undo/redo without modification.


Concepts: About Documents

Like other Swing components, a text component separates its data (known as the model ) from its view of the data. If you are not yet familiar with the model-view split used by Swing components, refer to Using Models (page 50).

A text component's model is known as a document and is an instance of a class that implements the Document [18] interface. A document provides these services for a text component:

[18] Document API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/text/Document.html.

  • Contains the text. A document stores the textual content in Element objects, which can represent any logical text structure, such as paragraphs, text runs that share styles, and so on. We do not cover Element s; however, the newsletter The Swing Connection has at least one article on the subject: http://java.sun.com/products/jfc/tsc/index.html.

  • Provides support for editing the text through the remove and insertString methods.

  • Notifies document listeners and undoable edit listeners of changes to the text.

  • Manages Position objects, which track a particular location within the text even as the text is modified.

  • Allows you to get information about the text, such as its length, and segments of the text as a string.

The Swing text package contains a subinterface of Document , StyledDocument , [19] that adds support for marking up the text with styles. One JTextComponent subclass, JTextPane , requires that its document be a StyledDocument rather than merely a Document .

[19] StyledDocument API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/text/StyledDocument.html.

The javax.swing.text package provides the following hierarchy of document classes, which implement specialized documents for the various JTextComponent subclasses.

Figure 17. The hierarchy of document classes that javax.swing.text provides.

graphics/03fig17.gif

A PlainDocument [20] is the default document for text fields, password fields, and text areas. PlainDocument provides a basic container for text where all the text is displayed in the same font. Even though an editor pane is a styled text component, it uses an instance of PlainDocument by default. The default document for a standard JTextPane is an instance of DefaultStyledDocument a container for styled text in no particular format. However, the document instance used by any particular editor pane or text pane depends on the type of content bound to it. If you use setPage to load text into an editor pane or text pane, the document instance used by the pane might change. Refer to How to Use Editor Panes and Text Panes (page 200) in Chapter 7 for details.

[20] PlainDocument API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/text/PlainDocument.html.

Although you can set the document of a text component, it's usually easier to let it be set automatically, and use a document filter if necessary to change how the text component's data is set. You can implement certain customizations either by installing a document filter or by replacing a text component's document with one of your own, For example, the text pane in TextComponentDemo has a document filter that limits the number of characters the text pane can contain.

Implementing a Document Filter

To implement a document filter, you create a subclass of DocumentFilter [21] and then attach it to a document using the setFilter method defined in AbstractDocument . [22] Although it's possible to have documents that don't descend from AbstractDocument , by default Swing text components use AbstractDocument subclasses for their documents.

[21] DocumentFilter API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/text/DocumentFilter.html.

[22] AbstractDocument API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/text/AbstractDocument.html.

The TextComponentDemo application has a document filter, DocumentSizeFilter , which limits the number of characters that the text pane can contain. Here's the code that creates the filter and attaches it to the text pane's document:

  ...//Where member variables are declared:  JTextPane textPane; AbstractDocument doc; static final int MAX_CHARACTERS = 300; ... textPane = new JTextPane(); ... StyledDocument styledDoc = textPane.getStyledDocument(); if (styledDoc instanceof AbstractDocument) {     doc = (AbstractDocument)styledDoc;     doc.setDocumentFilter(new DocumentSizeFilter(MAX_CHARACTERS)); } 

To limit the characters allowed in the document, DocumentSizeFilter overrides DocumentFilter 's insertString method, which is called each time text is inserted into the document. It also overrides the replace method, which is most likely to be called when the user changes text by pasting it in. In general, text insertion can be the result of the user typing or pasting text in, or because of a call to setText . Here's DocumentSizeFilter 's implementation of insertString :

 public void insertString(FilterBypass fb, int offs,                          String str, AttributeSet a)     throws BadLocationException {     if ((fb.getDocument().getLength() + str.length()) <= maxCharacters)         super.insertString(fb, offs, str, a);     else         Toolkit.getDefaultToolkit().beep(); } 

The code for replace is similar. The FilterBypass [23] parameter to the methods defined by DocumentFilter is simply an object that enables updating the document in a thread-safe way.

[23] FilterBypass API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/text/DocumentFilter.FilterBypass.html.

Because the preceding document filter is only concerned about additions to the document's data, it only overrides the insertString and replace methods. Most document filters would override DocumentFilter 's remove method, as well.

Listening for Changes on a Document

You can register two different types of listeners on a document: document listeners and undoable edit listeners. This subsection covers document listeners. For information about undoable edit listeners, refer to Implementing Undo and Redo (page 68).

A document notifies registered document listeners of changes to the document. Use a document listener to react when text is inserted or removed from a document, or when the style of some of the text changes.

The TextComponentDemo program uses a document listener to update the change log whenever a change is made to the text pane. The line of code that follows registers an instance of MyDocumentListener as a listener on the text pane's document:

 doc.addDocumentListener(new MyDocumentListener()); 

Here's the implementation of MyDocumentListener :

 protected class MyDocumentListener implements DocumentListener {     public void insertUpdate(DocumentEvent e) {         displayEditInfo(e);     }     public void removeUpdate(DocumentEvent e) {         displayEditInfo(e);     }     public void changedUpdate(DocumentEvent e) {         displayEditInfo(e);     }     private void displayEditInfo(DocumentEvent e) {             Document document = (Document)e.getDocument();             int changeLength = e.getLength();             changeLog.append(e.getType().toString() + ": "                 + changeLength + " character"                 + ((changeLength == 1) ? ". " : "s. ")                 + " Text length = " + document.getLength()                 + "." + newline);     } } 

The listener implements three methods for handling three different types of document events: insertion, removal, and style changes. StyledDocument s can fire all three types of events. PlainDocument s fire events only for insertion and removal. For general information about document listeners and document events, see How to Write a Document Listener (page 661) in Chapter 10.

Remember that the document filter for this text pane limits the number of characters allowed in the document. If you try to add more text than the document filter allows, the document filter blocks the change and the listener's insertUpdate method is not called. Document listeners are notified of changes only if the change has already occurred.

Sometimes, you might be tempted to change the document's text from within a document listener. However, you should never modify the contents of a text component from within a document listener. In fact, if you do, your program will likely deadlock! Instead, you can use a formatted text field or provide a document filter.

Listening for Caret and Selection Changes

The TextComponentDemo program uses a caret listener to display the current position of the caret or, if text is selected, the extent of the selection.

The caret listener class in this example is a JLabel subclass. Here's the code that creates the caret listener label and makes it a caret listener of the text pane:

 //Create the status area CaretListenerLabel caretListenerLabel = new CaretListenerLabel(                                                 "Caret Status"); ... textPane.addCaretListener(caretListenerLabel); 

A caret listener must implement one method, caretUpdate , which is called each time the caret moves or the selection changes. Here's the CaretListenerLabel implementation of caretUpdate :

 public void caretUpdate(CaretEvent e) {     //Get the location in the text     int dot = e.getDot();     int mark = e.getMark();     if (dot == mark) {  // no selection         try {             Rectangle caretCoords = textPane.modelToView(dot);             //Convert it to view coordinates             setText("caret: text position: " + dot +                     ", view location = [" + caretCoords.x +                     ", " + caretCoords.y + "]" + newline);         } catch (BadLocationException ble) {             setText("caret: text position: " + dot + newline);         }      } else if (dot < mark) {         setText("selection from: " + dot + " to " + mark + newline);      } else {         setText("selection from: " + mark + " to " + dot + newline);      } } 

As you can see, this listener updates its text label to reflect the current state of the caret or selection. The listener gets the information to display from the caret event object. For general information about caret listeners and caret events, see How to Write a Caret Listener (page 649) in Chapter 10.

As with document listeners, a caret listener is passive. It reacts to changes in the caret or in the selection but does not change the caret or the selection. If you want to change the caret or selection, then you should use a navigation filter or a custom caret instead.

Implementing a navigation filter is similar to implementing a document filter. First, you write a subclass of NavigationFilter . [24] You then attach an instance of it to a text component with the setNavigationFilter method.

[24] NavigationFilter API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/text/NavigationFilter.html.

You might create a custom caret to customize the appearance of a caret. To create a caret, write a class that implements the Caret [25] interfaceperhaps by extending the Default-Caret [26] class. Then provide an instance of your class as an argument to setCaret on a text component.

[25] Caret API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/text/Caret.html.

[26] DefaultCaret API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/text/DefaultCaret.html.

Concepts: About Editor Kits

Under the hood, text components use an EditorKit to tie the various pieces of the text component together. It provides the view factory, document, caret, and actions. An editor kit also reads and writes documents of a particular format. Although all text components use editor kits, some components hide theirs. You can't set or get the editor kit used by a text field or text area. Editor panes and text panes provide the getEditorKit method to get the current editor kit and the setEditorKit method to change it.

For all components, JTextComponent provides an API for you to indirectly invoke or customize some editor kit capabilities. For example, JTextComponent provides read and write methods, which invoke the editor kit's read and write methods. JTextComponent also provides a method, getActions , which returns all of the actions supported by a component.

The Swing text package provides the following editor kits:

DefaultEditorKit [27]

[27] DefaultEditorKit API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/text/DefaultEditorKit.html.

Reads and writes plain text, and provides a basic set of editing commands. Details of how the text system treats new lines are in the DefaultEditorKit API documentation. (To summarize: The " \n " character is used internally, but the document or platform line separators are used when writing files.) All of the other editor kits are descendants of DefaultEditorKit .

StyledEditorKit [28]

[28] StyledEditorKit API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/text/StyledEditorKit.html.

Reads and writes styled text, and provides a minimal set of actions for styled text. This class is a subclass of DefaultEditorKit and is the editor kit used by JTextPane by default.

HTMLEditorKit [29]

[29] HTMLEditorKit API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/text/html/HTMLEditorKit.html.

Reads, writes, and edits HTML. This is a subclass of StyledEditorKit .

RTFEditorKit

Reads, writes, and edits RTF. This is a subclass of StyledEditorKit .

Each of the editor kits above has been registered with the JEditorPane class and associated with the text format that the kit reads, writes, and edits. When a file is loaded into an editor pane, the pane checks the format of the file against its registered kits. If a registered kit is found that supports that file format, the pane uses the kit to read the file, display, and edit it. Thus, the editor pane effectively transforms itself into an editor for that text format. You can extend JEditorPane to support your own text format by creating an editor kit for it, and then using JEditorPane 's registerEditorKitForContentType to associate your kit with your text format.

The Text Component API

This section lists commonly used parts of the API shared by text components, much of it defined by the JTextComponent [30] class. The section Text Component Features (page 64) discussed how to use some of this API.

[30] JTextComponent API documentation: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/text/JTextComponent.html.

Also see the section The JComponent Class (page 53), which describes the API that text components inherit from JComponent . For information about the API for specific text components, see the relevant how-to section for the component.

For a complete listing of and further details about the text API, see the API documentation for JTextComponent and for the various classes and interfaces in the text package online at the following URL: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/text/package-summary.html.

Table 10. Setting Attributes These methods are in the JTextComponent class .

Method

Description

 void setDisabledTextColor(Color) Color getDisabledTextColor() 

Set or get the color used to display text when the text component is disabled.

 void setMargin(Insets) Insets getMargin() 

Set or get the margin between the text and the text compon-ent's border.

 void setEditable(boolean) boolean isEditable() 

Set or get whether the user can edit the text in the text component.

 void setDragEnabled(boolean) boolean getDragEnabled() 

Set or get the dragEnabled property, which must be true to enable drag handling on this component. The default value is false. See How to Use Drag and Drop and Data Transfer (page 545) in Chapter 9 for more details. Introduced in 1.4.

Table 11. Manipulating the Selection These methods are in the JTextComponent class .

Method

Description

String getSelectedText()

Get the currently selected text.

 void selectAll() void select(int, int) 

Select all text or select text within a start and end range.

 void setSelectionStart(int) void setSelectionEnd(int) int getSelectionStart() int getSelectionEnd() 

Set or get extent of the current selection by index.

 void setSelectedTextColor(Color) Color getSelectedTextColor() 

Set or get the color of selected text.

 void setSelectionColor(Color) Color getSelectionColor() 

Set or get the background color of selected text.

Table 12. Converting Positions between the Model and the View These methods are in the JTextComponent class .

Method

Description

int viewToModel(Point)

Convert the specified point in the view coordinate system to a position within the text.

Rectangle modelToView(int)

Convert the specified position within the text to a rectangle in the view coordinate system.

Table 13. Text Editing Commands

Class or Method

Description

 void cut() void copy() void paste() void replaceSelection(String) (  in  JTextComponent) 

Cut, copy, and paste text using the system clipboard.

EditorKit

Provides a text component's view factory, document, caret, and actions, as well as reading and writing documents of a particular format.

DefaultEditorKit

A concrete subclass of EditorKit that provides the basic text editing capabilities.

StyledEditorKit

A subclass of Default EditorKit that provides additional editing capabilities for styled text.

 String xxxxAction (  in  DefaultEditorKit) 

The names of all the actions supported by the default editor kit. See Associating Text Actions with Keystrokes (page 67).

 BeepAction CopyAction CutAction DefaultKeyTypedAction InsertBreakAction InsertContentAction InsertTabAction PasteAction (  in  DefaultEditorKit) 

Inner classes that implement various text editing commands.

 AlignmentAction BoldAction FontFamilyAction FontSizeAction ForegroundAction ItalicAction StyledTextAction UnderlineAction (  in  StyledEditorKit) 

Inner classes that implement various editing commands for styled text.

 Action[] getActions() (  in  JTextComponent) 

Get the actions supported by this component. This method gets the array of actions from the editor kit if one is used by the component.

 InputMap getInputMap() (  in  JComponent) 

Gets the input map that binds keystrokes to actions. See Associating Text Actions with Keystrokes (page 67).

 void put(KeyStroke, Object) (  in  InputMap) 

Binds the specified key to the specified action. You generally specify the action by its name, which for standard editing actions is represented by a string constant such as DefaultEditorKit.backwardAction .

Table 14. Classes and Interfaces That Represent Documents

Interface or Class

Description

Document

An interface that defines the API that must be implemented by all documents.

AbstractDocument

An abstract superclass implementation of the Document interface. This is the superclass for all documents provided by the Swing text package.

PlainDocument

A class that implements the Document interface. This is the default document for the plain text components (text field, password field, and text area). Additionally used by editor pane and text pane when loading plain text or text of an unknown format.

StyledDocument

A Document subinterface. Defines the API that must be implemented by documents that support styled text. JTextPane requires that its document be of this type.

DefaultStyledDocument

A class that implements the StyledDocument interface. The default document for JTextPane .

Table 15. Working with Documents

Class or Method

Description

DocumentFilter

The superclass of all document filters. You can use a document filter to change what gets inserted or removed from a document, without having to implement a document yourself. See Implementing a Document Filter (page 72).

 void setDocumentFilter(DocumentFilter) (  in  AbstractDocument) 

Set the document filter.

 void setDocument(Document) Document getDocument() (  in  JTextComponent) 

Set or get the document for a text component.

 Document createDefaultModel() (  in  JTextField  )  

Override this method to create a custom document instead of the default PlainDocument .

 void addDocumentListener(         DocumentListener) void removeDocumentListener(         DocumentListener) (  in  Document) 

Add or remove a document listener to a document. See Listening for Changes on a Document (page 73).

 void addUndoableEditListener(         UndoableEditListener) void removeUndoableEditListener(         UndoableEditlistener) (  in  Document) 

Add or remove an undoable edit listener to a document. Undoable edit listeners are used in Implementing Undo and Redo (page 68).

 int getLength() Position getStartPosition() Position getEndPosition() String getText(int, int) (  in  Document) 

Document methods that return useful information about the document.

 Object getProperty(Object) void putProperty(Object, Object) (  in  Document) void setDocumentProperties(Dictionary) Dictionary getDocumentProperties() (  in  AbstractDocument) 

A Document maintains a set of properties that you can manipulate with these methods. The example described in How to Use Text Fields (page 423) uses a property to name text components so that a shared document listener can identify the document that generated the event.

Table 16. Manipulating Carets and Selection Highlighters The methods in this table are defined in the JTextComponent class .

Interface, Class, or Method

Description

Caret

An interface that defines the API for objects that represent an insertion point within documents.

DefaultCaret

The default caret used by all text components.

 void setCaret(Caret) Caret getCaret() 

Set or get the caret object used by a text component.

 void setCaretColor(Color) Color getCaretColor() 

Set or get the color of the caret.

 void setCaretPosition(int) void moveCaretPosition(int) int getCaretPosition() 

Set or get the current position of the caret within the document.

 void addCaretListener(         CaretListener) void removeCaretListener(         CaretListener) 

Add or remove a caret listener to a text component.

NavigationFilter

The superclass for all navigation filters. A navigation filter lets you modify caret changes that are about to occur for a text component.

 void setNavigationFilter(          NavigationFilter) 

Attach a navigation filter to a text component.

Highlighter

An interface that defines the API for objects used to highlight the current selection.

DefaultHighlighter

The default highlighter used by all text components.

 void setHighlighter(Highlighter) Highlighter getHighlighter() 

Set or get the highlighter used by a text component.

Table 17. Reading and Writing Text

Method

Description

 void read(Reader, Object) void write(Writer) (  in  JTextComponent) 

Read or write text.

 void read(Reader, Document, int) void read(InputStream, Document, int) (  in  EditorKit) 

Read text from a stream into a document.

 void write(Writer, Document, int, int) void write(OutputStream, Document, int, int) (  in  EditorKit) 

Write text from a document to a stream.

 < Day Day Up > 


JFC Swing Tutorial, The. A Guide to Constructing GUIs
The JFC Swing Tutorial: A Guide to Constructing GUIs (2nd Edition)
ISBN: 0201914670
EAN: 2147483647
Year: 2004
Pages: 171

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