The JFC Swing Tutorial: A Guide to Constructing GUIs (2nd Edition)

 <  Day Day Up  >  

The JTextArea [190] class provides a component that displays multiple lines of text, optionally allowing the user to edit the text. If you need to obtain only one line of input from the user, you should use a text field instead. If you want the text area to display its text using multiple fonts or other styles, you should use an editor pane or text pane instead. If the displayed text has a limited length and is never edited by the user , consider using a label instead.

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

Many of this book's examples use uneditable text areas to display program output. Figure 84 is a picture of one that lets you enter text using a text field (at the top) and then appends the entered text to a text area (underneath).

Figure 84. The TextDemo application with two Groucho Marx quotations.

You can run TextDemo using Java Web Start or compile and run the example yourself. [191] Here's the code from TextDemo.java that creates and initializes the text area:

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

textArea = new JTextArea(5, 20); JScrollPane scrollPane = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); textArea.setEditable(false);

The two arguments to the JTextArea constructor are hints as to the number of rows and columns , respectively, the text area should display. The scroll pane that contains the text area pays attention to these hints when determining how big the scroll pane should be.

Without the creation of the scroll pane, the text area would not automatically scroll. The JScrollPane constructor shown in the preceding snippet sets up the text area for viewing in a scroll pane and specifies that the scroll pane's scroll bars should both always be visible. See How to Use Scroll Panes (page 325) if you want further information.

By default, text areas are editable. The code setEditable(false) makes the text area uneditable. It is still selectable and the user can copy data from it, but the user can't change the text area's contents directly.

The following code adds text to the text area. Note that the text system uses the \n character internally to represent newlines; for details, see the API documentation for Default- EditorKit . [192]

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

private final static String newline = "\n"; ... textArea.append(text + newline);

Unless the user has moved the caret (insertion point) by clicking or dragging in the text area, the text area automatically scrolls so that the appended text is visible. You can force the text area to scroll to the bottom by moving the caret to the end of the text area, like this, after the call to append :

textArea.setCaretPosition(textArea.getDocument().getLength());

Customizing Text Areas

You can customize text areas in several ways. For example, although a given text area can display text in only one font and color, you can (as for any component) set which font and color it uses. You can also determine how the text area wraps lines and the number of characters per tab. Finally, you can use the methods JTextArea inherits from JTextComponent to set properties such as the caret, support for dragging, selection color, and so on.

The following code, taken from TextSamplerDemo.java , [193] demonstrates initializing an editable text area. The text area uses the specified italic font and wraps lines between words.

[193] TextSamplerDemo.java is on the CD at: JavaTutorial/uiswing/components/example-1dot4/TextSamplerDemo.java .

JTextArea textArea = new JTextArea( "This is an editable JTextArea. " + "A text area is a \"plain\" text component, " + "which means that although it can display text " + "in any font, all of the text is in the same font." ); textArea.setFont(new Font("Serif", Font.ITALIC, 16)); textArea.setLineWrap(true); textArea.setWrapStyleWord(true);

By default, a text area doesn't wrap lines that are too long for the display area. Instead it uses one line for all the text between newline characters and ”if the text area is within a scroll pane ”allows itself to be scrolled horizontally. This example turns line wrapping on with a call to setLineWrap and then calls setWrapStyleWord to indicate that the text area should wrap lines at word boundaries rather than at character boundaries.

To provide scrolling capability, the example puts the text area in a scroll pane.

JScrollPane areaScrollPane = new JScrollPane(textArea); areaScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); areaScrollPane.setPreferredSize(new Dimension(250, 250));

You might have noticed that the JTextArea constructor used in this example does not specify the number of rows or columns. Instead, the code limits the size of the text area by setting the scroll pane's preferred size .

The Text Area API

Tables 93 through 95 list the commonly used JTextArea constructors and methods. Other methods you are likely to call are defined in JTextComponent and listed in The Text Component API (page 77). You should also refer to the JTextArea API documentation at: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JTextArea.html.

You might also invoke methods on a text area that it inherits from its other ancestors , such as setPreferredSize , setForeground , setBackground , setFont , and so on. See The JComponent Class (page 53) for tables of commonly used inherited methods.

Table 93. Setting or Getting Contents

Method or Constructor

Purpose

JTextArea() JTextArea(String) JTextArea(String, int, int) JTextArea(int, int)

Create a text area. When present, the String argument contains the initial text. The int arguments specify the desired width in columns and height in rows, respectively.

void setText(String) String getText() (defined in JTextComponent )

Set or get the text displayed by the text area.

Table 94. Fine-Tuning the Text Area's Appearance

Method

Purpose

void setEditable(boolean) boolean isEditable() (defined in JTextComponent )

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

void setColumns(int); int getColumns()

Set or get the number of columns displayed by the text area. This is really just a hint for computing the area's preferred width.

void setRows(int); int getRows()

Set or get the number of rows displayed by the text area. This is a hint for computing the area's preferred width.

int setTabSize(int)

Set the number of characters a tab is equivalent to.

int setLineWrap(boolean)

Set whether lines are wrapped if they are too long to fit within the allocated width. By default, this property is false and lines are not wrapped.

int setWrapStyleWord(boolean)

Set whether lines can be wrapped at white space (word boundaries) or at any character. By default, this property is false, and lines can be wrapped (if line wrapping is turned on) at any character.

Table 95. Implementing the Text Area's Functionality

Method

Purpose

void selectAll() (defined in JTextComponent )

Select all characters in the text area.

void append(String)

Add the specified text to the end of the text area.

void insert(String, int)

Insert the specified text at the specified position.

void replaceRange(String, int, int)

Replace the text between the indicated positions with the specified string.

int getLineCount() int getLineOfOffset(int) int getLineStartOffset(int) int getLineEndOffset(int)

Utilities for finding a line number or the position of the beginning or end of the specified line.

Examples That Use Text Areas

Many of this book's examples use JTextArea , typically to provide an area where events are logged. Here's a partial list of the demos that use text areas.

Example

Where Described

Notes

TextDemo

This section

An application that appends user-entered text to a text area.

TextSamplerDemo

Using Text Components (page 60)

Uses one of each of Swing's text components.

HtmlDemo

Using HTML in Swing Components (page 43)

A text area lets the user enter HTML code to be displayed in a label.

BasicDnD

How to Use Drag and Drop and Data Transfer (page 545)

Demonstrates built-in drag-and-drop functionality of several Swing components, including text areas.

ExtendedDnDDemo

How to Use Drag and Drop and Data Transfer (page 545)

Demonstrates dragging and dropping text between a text area, a list, and a table.

DragFileDemo

How to Use Drag and Drop and Data Transfer (page 545)

Demonstrates dragging file contents from a file chooser into a text area. A tabbed pane lets you easily switch between files.

FocusConceptsDemo

How to Use the Focus Subsystem (page 583)

Demonstrates how focus works, using a few components that include a text area.

 <  Day Day Up  >  

Категории