Documentation

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

How to Use Text Fields如何使用文本字段

A text field is a basic text control that enables the user to type a small amount of text. 文本字段是一个基本的文本控件,允许用户键入少量文本。When the user indicates that text entry is complete (usually by pressing Enter), the text field fires an action event. 当用户指示文本输入完成时(通常通过按Enter键),文本字段将触发一个操作事件If you need to obtain more than one line of input from the user, use a text area.如果需要从用户获得多行输入,请使用文本区域

The Swing API provides several classes for components that are either varieties of text fields or that include text fields.Swing API为组件提供了几个类,这些组件可以是各种文本字段,也可以包括文本字段。

JTextField What this section covers: basic text fields.本节内容:基本文本字段。
JFormattedTextField A JTextField subclass that allows you to specify the legal set of characters that the user can enter. JTextField子类,允许您指定用户可以输入的合法字符集。See How to Use Formatted Text Fields.请参阅如何使用格式化文本字段
JPasswordField A JTextField subclass that does not show the characters that the user types. JTextField子类,不显示用户键入的字符。See How to Use Password Fields.请参阅如何使用密码字段
JComboBox Can be edited, and provides a menu of strings to choose from. 可以编辑,并提供一个可供选择的字符串菜单。See How to Use Combo Boxes.查看如何使用组合框
JSpinner Combines a formatted text field with a couple of small buttons that enables the user to choose the previous or next available value. 将格式化文本字段与两个小按钮组合,使用户可以选择上一个或下一个可用值。See How to Use Spinners.请参阅如何使用微调器

The following example displays a basic text field and a text area. 以下示例显示基本文本字段和文本区域。The text field is editable. 文本字段是可编辑的。The text area is not editable. 文本区域不可编辑。When the user presses Enter in the text field, the program copies the text field's contents to the text area, and then selects all the text in the text field.当用户在文本字段中按Enter键时,程序将文本字段的内容复制到文本区域,然后选择文本字段中的所有文本。

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 sets up the text field:以下代码创建并设置文本字段:

textField = new JTextField(20);

The integer argument passed to the JTextField constructor, 20 in the example, indicates the number of columns in the field. 传递给JTextField构造函数的整数参数(本例中为20)表示字段中的列数。This number is used along with metrics provided by the field's current font to calculate the field's preferred width. 该数字与字段当前字体提供的度量一起用于计算字段的首选宽度。It does not limit the number of characters the user can enter. 它不限制用户可以输入的字符数。To do that, you can either use a formatted text field or a document listener, as described in Text Component Features.为此,可以使用格式化文本字段或文档侦听器,如文本组件功能中所述。


Note: 

We encourage you to specify the number of columns for each text field. 我们鼓励您为每个文本字段指定列数。If you do not specify the number of columns or a preferred size, then the field's preferred size changes whenever the text changes, which can result in unwanted layout updates.如果未指定列数或首选大小,则无论文本何时更改,字段的首选大小都会更改,这可能导致不需要的布局更新。


The next line of code registers a TextDemo object as an action listener for the text field.下一行代码将TextDemo对象注册为文本字段的操作侦听器。

textField.addActionListener(this);

The actionPerformed method handles action events from the text field:actionPerformed方法处理文本字段中的操作事件:

private final static String newline = "\n";
...
public void actionPerformed(ActionEvent evt) {
    String text = textField.getText();
    textArea.append(text + newline);
    textField.selectAll();
}

Notice the use of JTextField's getText method to retrieve the text currently contained by the text field. 注意,使用JTextFieldgetText方法检索文本字段当前包含的文本。The text returned by this method does not include a newline character for the Enter key that fired the action event.此方法返回的文本不包括触发操作事件的Enter键的换行符。

You have seen how a basic text field can be used. 您已经了解了如何使用基本文本字段。Because the JTextField class inherits from the JTextComponent class, text fields are very flexible and can be customized almost any way you like. 由于JTextField类继承自JTextComponent类,因此文本字段非常灵活,几乎可以以任何您喜欢的方式进行自定义。For example, you can add a document listener or a document filter to be notified when the text changes, and in the filter case you can modify the text field accordingly. 例如,可以添加文档监听器或文档筛选器,以便在文本更改时通知,在筛选器情况下,可以相应地修改文本字段。Information on text components can be found in Text Component Features. 有关文本组件的信息可在文本组件功能中找到。Before customizing a JTextField, however, make sure that one of the other components based on text fields will not do the job for you.但是,在自定义JTextField之前,请确保其他基于文本字段的组件中的一个不会为您完成这项工作。

Often text fields are paired with labels that describe the text fields. 通常,文本字段与描述文本字段的标签配对。See Examples That Use Text Fields for pointers on creating these pairs.请参阅使用文本字段作为创建这些对的指针的示例

Another Example: 另一个例子:TextFieldDemo

The TextFieldDemo example introduces a text field and a text area. TextFieldDemo示例引入了文本字段和文本区域。You can find the entire code for this program in TextFieldDemo.java.您可以在TextFieldDemo.java中找到该程序的完整代码。

As you type characters in the text field the program searches for the typed text in the text area. 在文本字段中键入字符时,程序将在文本区域中搜索键入的文本。If the entry is found it gets highlighted. 如果找到条目,它将被高亮显示。If the program fails to find the entry then the text field's background becomes pink. 如果程序未能找到条目,则文本字段的背景将变为粉红色。A status bar below the text area displays a message whether text is found or not. 文本区域下方的状态栏显示一条消息,无论是否找到文本。The Escape key is used to start a new search or to finish the current one. Here is a picture of the TextFieldDemo application.转义键用于启动新搜索或完成当前搜索。下面是TextFieldDemo应用程序的图片。

A snapshot of TextFieldDemo

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

Launches the TextFieldDemo Application

To highlight text, this example uses a highlighter and a painter. 为了突出显示文本,本示例使用了一个高亮灯和一个画笔。The code below creates and sets up the highlighter and the painter for the text area.下面的代码创建并设置文本区域的高亮灯和画笔。

final Highlighter hilit;
final Highlighter.HighlightPainter painter;
...
hilit = new DefaultHighlighter();
painter = new DefaultHighlighter.DefaultHighlightPainter(HILIT_COLOR);
textArea.setHighlighter(hilit);

This code adds a document listener to the text field's document.此代码将文档侦听器添加到文本字段的文档中。

entry.getDocument().addDocumentListener(this);

Document listener's insertUpdate and removeUpdate methods call the search method, which not only performs a search in the text area but also handles highlighting. 文档监听器的insertUpdateremoveUpdate方法调用search方法,该方法不仅在文本区域执行搜索,还处理高亮显示。The following code highlights the found text, sets the caret to the end of the found match, sets the default background for the text field, and displays a message in the status bar.以下代码高亮显示找到的文本,将插入符号设置为找到的匹配项的结尾,设置文本字段的默认背景,并在状态栏中显示消息。

hilit.addHighlight(index, end, painter);
textArea.setCaretPosition(end);
entry.setBackground(entryBg);
message("'" + s + "' found. Press ESC to end search");

The status bar is a JLabel object. 状态栏是一个JLabel对象。The code below shows how the message method is implemented.下面的代码显示了message方法是如何实现的。

private JLabel status;
...
void message(String msg) {
    status.setText(msg);
}

If there is no match in the text area, the following code changes the text field's background to pink and displays a proper information message.如果文本区域中没有匹配项,则以下代码将文本字段的背景更改为粉红色,并显示适当的信息消息。

entry.setBackground(ERROR_COLOR);
message("'" + s + "' not found. Press ESC to start a new search");

The CancelAction class is responsible for handling the Escape key as follows.CancelAction类负责处理转义键,如下所示。

class CancelAction extends AbstractAction {
       public void actionPerformed(ActionEvent ev) {
               hilit.removeAllHighlights();
               entry.setText("");
               entry.setBackground(entryBg);
           }
   }

The Text Field API文本字段API

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

You might also invoke methods on a text field inherited from the text field's 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 fields falls into these categories:使用文本字段的API分为以下几类:

Setting or Obtaining the Field's Contents设置或获取字段内容
Method or Constructor方法或构造函数 Purpose目的
JTextField()
JTextField(String)
JTextField(String, int)
JTextField(int)
Creates a text field. 创建文本字段。When present, the int argument specifies the desired width in columns. 如果存在,int参数指定所需的列宽度。The String argument contains the field's initial text.String参数包含字段的初始文本。
void setText(String)
String getText()
(defined in JTextComponent)
Sets or obtains the text displayed by the text field.设置或获取文本字段显示的文本。
Fine Tuning the Field's Appearance微调场的外观
Method方法 Purpose目的
void setEditable(boolean)
boolean isEditable()
(defined in JTextComponent)(在JTextComponent中定义)
Sets or indicates whether the user can edit the text in the text field.设置或指示用户是否可以编辑文本字段中的文本。
void setColumns(int);
int getColumns()
Sets or obtains the number of columns displayed by the text field. 设置或获取文本字段显示的列数。This is really just a hint for computing the field's preferred width.这实际上只是计算字段首选宽度的提示。
void setHorizontalAlignment(int);
int getHorizontalAlignment()
Sets or obtains how the text is aligned horizontally within its area. 设置或获取文本在其区域内的水平对齐方式。You can use JTextField.LEADING, JTextField.CENTER, and JTextField.TRAILING for arguments.可以使用JTextField.LEADINGJTextField.CENTERJTextField.TRAILING作为参数。
Implementing the Field's Functionality实现字段的功能
Method方法 Purpose目的
void addActionListener(ActionListener)
void removeActionListener(ActionListener)
Adds or removes an action listener.添加或删除操作侦听器。
void selectAll()
(defined in JTextComponent)
Selects all characters in the text field.选择文本字段中的所有字符。

Examples That Use Text Fields使用文本字段的示例

This table shows a few of the examples that use text fields and points to where those examples are described. 此表显示了一些使用文本字段的示例,并指出了这些示例的描述位置。For examples of code that are similar among all varieties of text fields such as dealing with layout, look at the example lists for related components such as formatted text fields and spinners.有关各种文本字段(如处理布局)之间类似的代码示例,请查看相关组件(如格式化文本字段微调器)的示例列表。

Example示例 Where Described描述位置 Notes备注
TextDemo This section本节 An application that uses a basic text field with an action listener.使用基本文本字段和操作侦听器的应用程序。
TextFieldDemo This section本节 An application that uses a text field and a text area. 使用文本字段和文本区域的应用程序。A search is made in the text area to find an entry from the text field.在文本区域中进行搜索以从文本字段中查找条目。
DialogDemo How to Make Dialogs如何制作对话 CustomDialog.java includes a text field whose value is checked. 包括其值已检查的文本字段。You can bring up the dialog by clicking the More Dialogs tab, selecting the Input-validating dialog option, and then clicking the Show it! button.您可以通过单击“更多对话框”选项卡,选择“输入验证对话框”选项,然后单击“显示它!”按钮来打开对话框
TextSamplerDemo Using Text Components使用文本组件 Lays out label-text field pairs using a GridBagLayout and a convenience method:使用GridBagLayout和方便的方法布局标签文本字段对:
addLabelTextRows(JLabel[] labels,
                 JTextField[] textFields,
                 GridBagLayout gridbag,
                 Container container)
TextInputDemo How to Use Formatted Text Fields如何使用格式化文本字段 Lays out label-text field pairs using a SpringLayout and a SpringUtilities convenience method:使用SpringLayoutSpringUtilities方便方法布局标签文本字段对:
makeCompactGrid(Container parent,
                int rows, int cols,
                int initialX, int initialY,
                int xPad, int yPad)

If you are programming in JavaFX, see Text Field.如果您使用JavaFX编程,请参阅文本字段


Previous page: How to Use Text Areas
Next page: How to Use Tool Bars