The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
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
的示例的图片,它允许您使用文本字段(顶部)键入文本,然后将键入的文本附加到文本区域(底部)。
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.或者,要自己编译和运行示例,请参考示例索引。
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 请注意,文本系统在内部使用“\n”字符表示换行符;有关详细信息,请参阅DefaultEditorKit
.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());
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.相反,代码通过设置滚动窗格的首选大小来限制文本区域的大小。
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
应用程序的图片。
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.或者,要自己编译和运行示例,请参考示例索引。
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 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. setPreferredSize
、setForeground
、setBackground
、setFont
等。See The JComponent Class for tables of commonly used inherited methods.有关常用继承方法的表,请参阅JComponent
类。
The API for using text areas includes the following categories:使用文本区域的API包括以下类别:
JTextArea() JTextArea(String) JTextArea(String, int, int) JTextArea(int, int) |
String argument contains the initial text. String 参数包含初始文本。int arguments specify the desired width in columns and height in rows, respectively.int 参数分别指定所需的列宽度和行高度。 |
void setText(String) String getText() (defined in JTextComponent ) |
void setEditable(boolean) boolean isEditable() (defined in JTextComponent ) |
|
void setColumns(int); int getColumns() |
|
void setRows(int); int getRows() |
|
int setTabSize(int) |
|
int setLineWrap(boolean) |
false ,并且不换行。 |
int setWrapStyleWord(boolean) |
false ,并且可以在任何字符处换行(如果启用换行)。 |
void selectAll() (defined in JTextComponent ) |
|
void append(String) |
|
void insert(String, int) |
|
void replaceRange(String, int, int) |
|
int getLineCount() int getLineOfOffset(int) int getLineStartOffset(int) int getLineEndOffset(int) |
This table lists examples that use text areas and points to where those examples are described.下表列出了使用文本区域的示例,并指出了这些示例的描述位置。
TextDemo |
||
TextAreaDemo |
||
TextSamplerDemo |
||
HtmlDemo |
||
BasicDnD |
||
FocusConceptsDemo |