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发行说明。
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.如果需要从用户获得多行输入,请使用文本区域。
JTextField
|
|
JFormattedTextField |
JTextField subclass that allows you to specify the legal set of characters that the user can enter. JTextField 子类,允许您指定用户可以输入的合法字符集。 |
JPasswordField |
JTextField subclass that does not show the characters that the user types. JTextField 子类,不显示用户键入的字符。 |
JComboBox |
|
JSpinner |
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键时,程序将文本字段的内容复制到文本区域,然后选择文本字段中的所有文本。
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 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.为此,可以使用格式化文本字段或文档侦听器,如文本组件功能中所述。
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. JTextField
的getText
方法检索文本字段当前包含的文本。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.请参阅使用文本字段作为创建这些对的指针的示例。
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
应用程序的图片。
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.或者,要自己编译和运行示例,请参考示例索引。
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. insertUpdate
和removeUpdate
方法调用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 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. setPreferredSize
、setForeground
、setBackground
、setFont
等。See The JComponent Class for tables of commonly used inherited methods.有关常用继承方法的表,请参阅JComponent
类。
The API for using text fields falls into these categories:使用文本字段的API分为以下几类:
JTextField() JTextField(String) JTextField(String, int) JTextField(int) |
int argument specifies the desired width in columns. int 参数指定所需的列宽度。String argument contains the field's initial text.String 参数包含字段的初始文本。 |
void setText(String) String getText() (defined in JTextComponent ) |
void setEditable(boolean) boolean isEditable() JTextComponent )JTextComponent 中定义) |
|
void setColumns(int); int getColumns() |
|
void setHorizontalAlignment(int); int getHorizontalAlignment() |
JTextField.LEADING , JTextField.CENTER , and JTextField.TRAILING for arguments.JTextField.LEADING 、JTextField.CENTER 和JTextField.TRAILING 作为参数。 |
void addActionListener(ActionListener) void removeActionListener(ActionListener) |
|
void selectAll() (defined in JTextComponent ) |
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.有关各种文本字段(如处理布局)之间类似的代码示例,请查看相关组件(如格式化文本字段和微调器)的示例列表。
TextDemo |
||
TextFieldDemo |
||
DialogDemo |
CustomDialog.java | |
TextSamplerDemo |
GridBagLayout and a convenience method:GridBagLayout 和方便的方法布局标签文本字段对:
addLabelTextRows(JLabel[] labels, JTextField[] textFields, GridBagLayout gridbag, Container container) | |
TextInputDemo |
SpringLayout and a SpringUtilities convenience method:SpringLayout 和SpringUtilities 方便方法布局标签文本字段对:
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编程,请参阅文本字段。