Documentation

The Java™ Tutorials
Hide TOC
How to Use Text Areas如何使用文本区域
Trail: Creating a GUI With Swing
Lesson: Using Swing Components
Section: How to Use Various Components

How to Use Text Areas如何使用文本区域

The JTextArea class provides a component that displays multiple lines of text and optionally allows the user to edit the text. JTextArea类提供了一个显示多行文本的组件,并允许用户编辑文本。If you need to obtain only one line of input from the user, you should use a text field. 如果只需要从用户获得一行输入,则应使用文本字段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. 如果希望文本区域使用多种字体或其他样式显示其文本,则应使用编辑器窗格或文本窗格If the displayed text has a limited length and is never edited by the user, use a label.如果显示的文本长度有限且用户从未编辑过,请使用标签

Many of the Tutorial's examples use uneditable text areas to display program output. 本教程的许多示例使用不可编辑的文本区域来显示程序输出。Here is a picture of an example called TextDemo that enables you to type text using a text field (at the top) and then appends the typed text to a text area (underneath).下面是一个名为TextDemo的示例的图片,它允许您使用文本字段(顶部)键入文本,然后将键入的文本附加到文本区域(底部)。

A snapshot of TextDemo

Click the Launch button to run TextDemo using Java™ Web Start (download JDK 7 or later). 单击启动按钮,使用Java™Web启动运行TextDemo(下载JDK 7或更高版本)。Alternatively, to compile and run the example yourself, consult the example index.或者,要自己编译和运行示例,请参考示例索引

Launches the TextDemo application

You can find the entire code for this program in TextDemo.java. 您可以在TextDemo.java中找到该程序的全部代码。The following code creates and initializes the text area:以下代码创建并初始化文本区域:

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

The two arguments to the JTextArea constructor are hints as to the number of rows and columns, respectively, that the text area should display. JTextArea构造函数的两个参数分别是关于文本区域应显示的行数和列数的提示。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 be visible when needed. 前面代码段中显示的JScrollPane构造函数设置了在滚动窗格中查看的文本区域,并指定在需要时滚动窗格的滚动条应可见。See How to Use Scroll Panes if you want further information.如果需要更多信息,请参阅如何使用滚动窗格

Text areas are editable by default. 默认情况下,文本区域是可编辑的。The code setEditable(false) makes the text area uneditable. 代码setEditable(false)使文本区域不可编辑。It is still selectable and the user can copy data from it, but the user cannot 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 DefaultEditorKit.请注意,文本系统在内部使用“\n”字符表示换行符;有关详细信息,请参阅DefaultEditorKit的API文档。

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 after the call to append:您可以通过在调用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 set which font and color it uses. 例如,虽然给定的文本区域只能以一种字体和颜色显示文本,但您可以设置它使用的字体和颜色。This customization option can be performed on any component. 此自定义选项可以在任何组件上执行。You can also determine how the text area wraps lines and the number of characters per tab. 您还可以确定文本区域如何换行以及每个选项卡的字符数。Finally, you can use the methods that the JTextArea class inherits from the JTextComponent class to set properties such as the caret, support for dragging, or color selection.最后,您可以使用JTextArea类从JTextComponent类继承的方法来设置属性,如插入符号、拖动支持或颜色选择。

The following code taken from TextSamplerDemo.java demonstrates initializing an editable text area. 以下代码取自TextSamplerDemo.java,演示如何初始化可编辑文本区域。The text area uses the specified italic font, and wraps lines between words.文本区域使用指定的斜体字体,并在单词之间换行。

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 does not 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 the setLineWrap method and then calls the setWrapStyleWord method to indicate that the text area should wrap lines at word boundaries rather than at character boundaries.此示例通过调用setLineWrap方法打开换行,然后调用setWrapStyleWord方法以指示文本区域应在单词边界而不是字符边界换行。

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. 您可能已经注意到,本示例中使用的JTextArea构造函数没有指定行数或列数。Instead, the code limits the size of the text area by setting the scroll pane's preferred size.相反,代码通过设置滚动窗格的首选大小来限制文本区域的大小。

Another Example: TextAreaDemo另一个例子:TextAreaDemo

The TextAreaDemo example introduces an editable text area with a special feature — a word completion function. TextAreaDemo示例引入了具有特殊功能的可编辑文本区域;一个字完成功能。As the user types in words, the program suggests hints to complete the word whenever the program's vocabulary contains a word that starts with what has been typed. 当用户键入单词时,只要程序的词汇表中包含以已键入的单词开头的单词,程序就会提示完成该单词。Here is a picture of the TextAreaDemo application.下面是TextAreaDemo应用程序的图片。

A snapshot of TextAreaDemo

Click the Launch button to run TextAreaDemo using Java™ Web Start (download JDK 7 or later). 单击启动按钮,使用Java™Web启动运行TextAreaDemo(下载JDK 7或更高版本)。Alternatively, to compile and run the example yourself, consult the example index.或者,要自己编译和运行示例,请参考示例索引

Launches the TextAreaDemo Application

You can find the entire code for this program in TextAreaDemo.java.您可以在TextAreaDemo.java中找到该程序的完整代码。

This example provides a scrolling capacity for the text area with the default scroll bar policy. 本示例使用默认滚动条策略为文本区域提供滚动能力。By default, the vertical scroll bar only appears when the display area is entirely filled with text and there is no room to append new words. 默认情况下,垂直滚动条仅在显示区域完全充满文本且没有空间添加新词时显示。You can provide a scroll pane of this type with the following code:您可以使用以下代码提供这种类型的滚动窗格:

textArea.setWrapStyleWord(true);
  jScrollPane1 = new JScrollPane(textArea);

As mentioned above, the text area is editable. 如上所述,文本区域是可编辑的。You can play with the text area by typing and pasting text, or by deleting some parts of text or the entire content. 您可以通过键入和粘贴文本,或删除部分文本或整个内容来播放文本区域。Also try using standard key bindings for editing text within the text area.还可以尝试使用标准键绑定来编辑文本区域中的文本。

Now explore how the word completion function is implemented. 现在探索如何实现单词补全功能。Type in a word like "Swing" or "special". 输入“Swing”或“special”等词。As soon as you have typed "sw" the program shows a possible completion "ing" highlighted in light-blue. 输入“sw”后,程序将显示一个可能的完成“ing”,以浅蓝色突出显示。Press Enter to accept the completion or continue typing.Enter键接受完成或继续键入。

The following code adds a document listener to the text area's document:以下代码将文档侦听器添加到文本区域的文档中:

textArea.getDocument().addDocumentListener(this);

When you started typing a word, the insertUpdate method checks whether the program's vocabulary contains the typed prefix. 开始键入单词时,insertUpdate方法检查程序的词汇表是否包含键入的前缀。Once a completion for the prefix is found, a call to the invokeLater method submits a task for changing the document later. 一旦找到前缀的完成,调用invokeLater方法将提交一个任务,以便稍后更改文档。It is important to remember that you cannot modify the document from within the document event notification, otherwise you will get an exception. 请记住,您不能在文档事件通知中修改文档,否则会出现异常。Examine the following code below.检查下面的代码。

String prefix = content.substring(w + 1).toLowerCase();
int n = Collections.binarySearch(words, prefix);
if (n < 0 && -n <= words.size()) {
    String match = words.get(-n - 1);
    if (match.startsWith(prefix)) {
        // A completion is found
        String completion = match.substring(pos - w);
        // We cannot modify Document from within notification,
        // so we submit a task that does the change later
        SwingUtilities.invokeLater(
            new CompletionTask(completion, pos + 1));
    }
} else {
    // Nothing found
    mode = Mode.INSERT;
}

The code shown in bold illustrates how the selection is created. 粗体显示的代码说明了如何创建选择。The caret is first set to the end of the complete word, then moved back to a position after the last character typed. 插入符号首先设置为完整单词的结尾,然后移回键入的最后一个字符后的位置。The moveCaretPosition method not only moves the caret to a new position but also selects the text between the two positions. moveCaretPosition方法不仅将插入符号移动到新位置,而且还选择两个位置之间的文本。The completion task is implemented with the following code:完成任务使用以下代码实现:

private class CompletionTask implements Runnable {
        String completion;
        int position;
        
        CompletionTask(String completion, int position) {
            this.completion = completion;
            this.position = position;
        }
        
        public void run() {
            textArea.insert(completion, position);
textArea.setCaretPosition(position + completion.length());
            textArea.moveCaretPosition(position);
            mode = Mode.COMPLETION;
        }
    }

The Text Area API文本区域API

The following tables list the commonly used JTextArea constructors and methods. 下表列出了常用的JTextArea构造函数和方法。Other methods you are likely to call are defined in JTextComponent, and listed in The Text Component API.您可能调用的其他方法在JTextComponent中定义,并在文本组件API中列出。

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. 您还可以调用从其他祖先继承的文本区域上的方法,如setPreferredSizesetForegroundsetBackgroundsetFont等。See The JComponent Class for tables of commonly used inherited methods.有关常用继承方法的表,请参阅JComponent

The API for using text areas includes the following categories:使用文本区域的API包括以下类别:

Setting or Obtaining Contents设置或获取内容
Method or Constructor方法或构造函数 Purpose目的
JTextArea()
JTextArea(String)
JTextArea(String, int, int)
JTextArea(int, int)
Creates a text area. 创建文本区域。When present, the String argument contains the initial text. 如果存在,String参数包含初始文本。The int arguments specify the desired width in columns and height in rows, respectively.int参数分别指定所需的列宽度和行高度。
void setText(String)
String getText()
(defined in JTextComponent)
Sets or obtains the text displayed by the text area.设置或获取文本区域显示的文本。
Fine Tuning the Text Area's Appearance微调文本区域的外观
Method方法 Purpose目的
void setEditable(boolean)
boolean isEditable()
(defined in JTextComponent)
Sets or indicates whether the user can edit the text in the text area.设置或指示用户是否可以编辑文本区域中的文本。
void setColumns(int);
int getColumns()
Sets or obtains 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()
Sets or obtains the number of rows displayed by the text area. 设置或获取文本区域显示的行数。This is a hint for computing the area's preferred height.这是计算区域首选高度的提示。
int setTabSize(int) Sets the number of characters a tab is equivalent to.设置选项卡所对应的字符数。
int setLineWrap(boolean) Sets 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.默认情况下,此属性为false,并且不换行。
int setWrapStyleWord(boolean) Sets 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.默认情况下,此属性为false,并且可以在任何字符处换行(如果启用换行)。
Implementing the Text Area's Functionality实现文本区域的功能
Method方法 Purpose目的
void selectAll()
(defined in JTextComponent)
Selects all characters in the text area.选择文本区域中的所有字符。
void append(String) Adds the specified text to the end of the text area.将指定的文本添加到文本区域的末尾。
void insert(String, int) Inserts the specified text at the specified position.在指定位置插入指定文本。
void replaceRange(String, int, int) Replaces 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使用文本区域的示例

This table lists examples that use text areas and points to where those examples are described.下表列出了使用文本区域的示例,并指出了这些示例的描述位置。

Example示例 Where Described描述位置 Notes备注
TextDemo This section本节 An application that appends user-entered text to a text area.将用户输入的文本附加到文本区域的应用程序。
TextAreaDemo This section本节 An application that has a text area with a word completion function.一种应用程序,它有一个带有单词补全功能的文本区域。
TextSamplerDemo Using Text Components使用文本组件 Uses one of each Swing text components.使用每个Swing文本组件中的一个。
HtmlDemo How to Use HTML in Swing Components如何在Swing组件中使用HTML A text area that enables the user to type HTML code to be displayed in a label.一个文本区域,允许用户键入要在标签中显示的HTML代码。
BasicDnD Introduction to DnDDnD简介 Demonstrates built-in drag-and-drop functionality of several Swing components, including text areas.演示几个Swing组件的内置拖放功能,包括文本区域。
FocusConceptsDemo How to Use the Focus Subsystem如何使用焦点子系统 Demonstrates how focus works using a few components that include a text area.演示焦点如何使用包含文本区域的几个组件工作。

Previous page: How to Use Tables
Next page: How to Use Text Fields