Documentation

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

How to Use Formatted Text Fields如何使用格式化文本字段

Formatted text fields provide a way for developers to specify the valid set of characters that can be typed in a text field. 格式化文本字段为开发人员提供了一种方法,可以指定可以在文本字段中键入的有效字符集。Specifically, the JFormattedTextField class adds a formatter and an object value to the features inherited from the JTextField class. 具体来说,JFormattedTextField类将格式化程序和对象添加到从JTextField类继承的特性中。The formatter translates the field's value into the text it displays, and the text into the field's value.格式化程序将字段值转换为显示的文本,并将文本转换为字段值。

Using the formatters that Swing provides, you can set up formatted text fields to type dates and numbers in localized formats. 使用Swing提供的格式化程序,您可以设置格式化文本字段,以本地化格式键入日期和数字。Another kind of formatter enables you to use a character mask to specify the set of characters that can be typed at each position in the field. 另一种格式化程序允许您使用字符掩码来指定可以在字段中每个位置键入的字符集。For example, you can specify a mask for typing phone numbers in a particular format, such as (XX) X-XX-XX-XX-XX.例如,您可以指定用于以特定格式键入电话号码的掩码,例如(XX)X-XX-XX-XX-XX。

If the possible values of a formatted text field have an obvious order, use a spinner instead. 如果格式化文本字段的可能值具有明显的顺序,请改用微调器A spinner uses a formatted text field by default, but adds two buttons that enable the user to choose a value in a sequence.默认情况下,微调器使用格式化的文本字段,但添加了两个按钮,允许用户选择序列中的值。

Another alternative or adjunct to using a formatted text field is installing an input verifier on the field. 使用格式化文本字段的另一种替代或附加方法是在字段上安装输入验证器A component's input verifier is called when the component nearly loses the keyboard focus. 当组件几乎失去键盘焦点时,调用组件的输入验证器。The input verifier enables you to check whether the value of the component is valid and optionally change it or stop the focus from being transferred.输入验证器使您能够检查组件的值是否有效,并可以选择更改它或停止焦点转移。

This GUI uses formatted text fields to display numbers in four different formats.此GUI使用格式化文本字段以四种不同格式显示数字。

A snapshot of FormattedTextFieldDemo

Try this:试试这个: 
  1. Click the Launch button to run FormattedTextFieldDemo 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 FormattedTextFieldDemo Application
  2. Experiment with different loan amounts, annual percentage rates (APRs), and loan lengths.尝试不同的贷款金额、年利率(APR)和贷款期限。
    Note that as long as the text you type is valid, the Month Payment field is updated when you press Enter or move the focus out of the field that you are editing.请注意,只要键入的文本有效,按Enter键或将焦点移出正在编辑的字段时,“月付款”字段就会更新。
  3. Type invalid text such as "abcd" in the Loan Amount field and then press Enter.在“贷款金额”字段中键入无效文本,如“abcd”,然后按Enter键。
    The Month Payment field remains the same. 月付款字段保持不变。When you move the focus from the Loan Amount field, the text reverts to the field's last valid value.当您从“贷款金额”字段中移动焦点时,文本将恢复为该字段的最后一个有效值。
  4. Type marginally valid text such as "2000abcd" in the Loan Amount field and press Enter.在贷款金额字段中键入边缘有效的文本,如“2000abcd”,然后按Enter键。
    The Monthly Payment field is updated, though the Loan Amount field still displays 2000abcd. “每月付款”字段已更新,但“贷款金额”字段仍显示2000abcdWhen you move the focus from the Loan Amount field, the text it displays is updated to a neatly formatted version of its value, for example, "2,000".当您将焦点从“贷款金额”字段移开时,它显示的文本将更新为其值的格式整洁的版本,例如“2000”。

You can find the entire code for this program in FormattedTextFieldDemo.java. 您可以在FormattedTextFieldDemo.java中找到该程序的完整代码。This code creates the first field.此代码创建第一个字段。

amountField = new JFormattedTextField(amountFormat);
amountField.setValue(new Double(amount));
amountField.setColumns(10);
amountField.addPropertyChangeListener("value", this);
...
amountFormat = NumberFormat.getNumberInstance();

The constructor used to create the amountField object takes a java.text.Format argument. 用于创建amountField对象的构造函数采用java.text.Format参数。The Format object is used by the field's formatter to translate the field's value to text and the text to the field's value.字段的格式化程序使用Format对象将字段值转换为文本,并将文本转换为字段值。

The remaining code sets up the amountField object. 剩下的代码设置amountField对象。The setValue method sets the field's value property to a floating-point number represented as a Double object. setValue方法将字段的value属性设置为以Double对象表示的浮点数。The setColumns method, inherited from the JTextField class, hints about the preferred size of the field. JTextField类继承的setColumns方法提示了字段的首选大小。The call to the addPropertyChangeListener method registers a listener for the value property of the field, so the program can update the Monthly Payment field whenever the user changes the loan amount.addPropertyChangeListener方法的调用为字段的value属性注册了一个监听器,因此每当用户更改贷款金额时,程序都可以更新每月付款字段。

The rest of this section covers the following topics:本节其余部分包括以下主题:

This section does not explain the API inherited from the JTextField class. 本节不解释从JTextField类继承的API。That API is described in How to Use Text Fields.该API在如何使用文本字段中进行了描述。

Creating and Initializing Formatted Text Fields创建和初始化格式化文本字段

The following code creates and initializes the remaining three fields in the FormattedTextFieldDemo example.下面的代码创建并初始化FormattedTextFieldDemo示例中的其余三个字段。

rateField = new JFormattedTextField(percentFormat);
rateField.setValue(new Double(rate));
rateField.setColumns(10);
rateField.addPropertyChangeListener("value", this);

numPeriodsField = new JFormattedTextField();
numPeriodsField.setValue(new Integer(numPeriods));
numPeriodsField.setColumns(10);
numPeriodsField.addPropertyChangeListener("value", this);

paymentField = new JFormattedTextField(paymentFormat);
paymentField.setValue(new Double(payment));
paymentField.setColumns(10);
paymentField.setEditable(false);
paymentField.setForeground(Color.red);

...
percentFormat = NumberFormat.getNumberInstance();
percentFormat.setMinimumFractionDigits(2);

paymentFormat = NumberFormat.getCurrencyInstance();

The code for setting up the rateField object is almost identical to the code listed previously for other fields. 设置rateField对象的代码与前面列出的其他字段的代码几乎相同。The only difference is that the format is slightly different, thanks to the code percentFormat.setMinimumFractionDigits(2).唯一的区别是,由于代码percentFormat.setMinimumFractionDigits(2),格式略有不同。

The code that creates the numPeriodsField object does not explicitly set a format or formatter. 创建numPeriodsField对象的代码没有显式设置格式或格式化程序。Instead, it sets the value to an Integer and enables the field to use the default formatter for Integer objects. 相反,它将值设置为Integer,并使字段能够使用Integer对象的默认格式化程序。The code did not do this in the previous two fields because the default formatter is not being used for Double objects. 代码没有在前两个字段中执行此操作,因为默认格式化程序未用于Double对象。The result was not what was needed. How to specify formats and formatters is covered later in this section.结果不是所需要的。本节后面将介绍如何指定格式和格式化程序。

The payment field is different from the other fields because it is uneditable, uses a different color for its text, and does not have a property change listener. 付款字段与其他字段不同,因为它不可编辑,文本使用不同的颜色,并且没有属性更改侦听器。Otherwise, it is identical to the other fields. 否则,它与其他字段相同。We could have chosen to use a text field or label instead. 我们可以选择使用文本字段或标签。Whatever the component, we could still use the paymentFormat method to parse the payment amount into the text to be displayed.无论组件是什么,我们仍然可以使用paymentFormat方法将付款金额解析为要显示的文本。

Setting and Getting the Field's Value设置和获取字段值

Keep the following in mind when using a formatted text field:使用格式化文本字段时,请记住以下内容:


A formatted text field's text and its value are two different properties, and the value often lags behind the text.格式化文本字段的textvalue是两个不同的属性,并且该值通常滞后于文本。


The text property is defined by the JTextField class. text属性由JTextField类定义。This property always reflects what the field displays. 此属性始终反映字段显示的内容。The value property, defined by the JFormattedTextField class, might not reflect the latest text displayed in the field. JFormattedTextField类定义的value属性可能不会反映字段中显示的最新文本。While the user is typing, the text property changes, but the value property does not change until the changes are committed.用户键入时,文本属性会更改,但值属性在提交更改之前不会更改。

To be more precise, the value of a formatted text field can be set by using either the setValue method or the commitEdit method. 更准确地说,格式化文本字段的值可以通过使用setValue方法或commitEdit方法来设置。The setValue method sets the value to the specified argument. setValue方法将值设置为指定的参数。The argument can technically be any Object, but the formatter needs to be able to convert it into a string. 从技术上讲,参数可以是任何Object,但格式化程序需要能够将其转换为字符串。Otherwise, the text field does not display any substantive information.否则,文本字段不显示任何实质性信息。

The commitEdit method sets the value to whatever object the formatter determines is represented by the field's text. commitEdit方法将值设置为格式化程序确定由字段文本表示的任何对象。The commitEdit method is automatically called when either of the following happens:当发生以下任一情况时,将自动调用commitEdit方法:


Note: 

Some formatters might update the value constantly, rendering the loss of focus meaningless, as the value is always the same as what the text specifies.一些格式化程序可能会不断更新该值,使焦点丢失变得毫无意义,因为该值始终与文本指定的值相同。


When you set the value of a formatted text field, the field's text is updated to reflect the value. 设置格式化文本字段的值时,字段的文本将更新以反映该值。Exactly how the value is represented as text depends on the field's formatter.值以文本形式表示的确切方式取决于字段的格式化程序。

Note that although the JFormattedTextField class inherits the setText method from the JTextField class, you do not usually call the setText method on a formatted text field. 请注意,尽管JFormattedTextField类从JTextField类继承了setText方法,但您通常不会在格式化的文本字段上调用setText方法。If you do, the field's display changes accordingly but the value is not updated (unless the field's formatter updates it constantly).如果这样做,则字段的显示会相应更改,但值不会更新(除非字段的格式化程序不断更新)。

To obtain a formatted text field's current value, use the getValue method. 要获取格式化文本字段的当前值,请使用getValue方法。If necessary, you can ensure that the value reflects the text by calling the commitEdit method before getValue. 如有必要,可以通过在getValue之前调用commitEdit方法来确保值反映文本。Because the getValue method returns an Object, you need to cast it to the type used for your field's value. 因为getValue方法返回一个Object,所以需要将其转换为用于字段值的类型。For example:例如:

Date enteredDate = (Date)dateField.getValue();

To detect changes in a formatted text field's value, you can register a property change listener on the formatted text field to listen for changes to the "value" property. 要检测格式化文本字段值的更改,可以在格式化文本字段上注册属性更改侦听器,以侦听“值”属性的更改。The property change listener is taken from the FormattedTextFieldDemo example:属性更改侦听器取自FormattedTextFieldDemo示例:

//The property change listener is registered on each
//field using code like this:
//    someField.addPropertyChangeListener("value", this);

/** Called when a field's "value" property changes. */
public void propertyChange(PropertyChangeEvent e) {
    Object source = e.getSource();
    if (source == amountField) {
        amount = ((Number)amountField.getValue()).doubleValue();
    } else if (source == rateField) {
        rate = ((Number)rateField.getValue()).doubleValue();
    } else if (source == numPeriodsField) {
        numPeriods = ((Number)numPeriodsField.getValue()).intValue();
    }

    double payment = computePayment(amount, rate, numPeriods);
    paymentField.setValue(new Double(payment));
}

Specifying Formats指定格式

The Format class provides a way to format locale-sensitive information such as dates and numbers. Format类提供了一种格式化区域设置敏感信息(如日期和数字)的方法。Formatters that descend from the InternationalFormatter class, such as the DateFormatter and NumberFormatter classes, use Format objects to translate between the field's text and value. InternationalFormatter类派生的格式化程序,如DateFormatterNumberFormatter,使用Format对象在字段的文本和值之间进行转换。You can obtain a Format object by calling one of the factory methods in the DateFormat or NumberFormat classes, or by using one of the SimpleDateFormat constructors.您可以通过调用DateFormatNumberFormat类中的一个工厂方法,或者通过使用SimpleDateFormat构造函数之一,来获取Format对象。


Note: 

A third commonly used formatter class, MaskFormatter, does not descend from the InternationalFormatter class and does not use formats. 第三个常用的格式化程序类MaskFormatter不从InternationalFormatter类派生,也不使用格式。The MaskFormatter is discussed in Using MaskFormatter.使用MaskFormatter中讨论了MaskFormetter


You can customize certain format aspects when you create the Format object, and others through a format-specific API. 您可以在创建Format对象时自定义某些格式方面,也可以通过特定于格式的API自定义其他方面。For example, DecimalFormat objects, which inherit from NumberFormat and are often returned by its factory methods, can be customized by using the setMaximumFractionDigits and setNegativePrefix methods. 例如,可以使用setMaximumFractionDigitssetNegativePrefix方法自定义从NumberFormat继承并通常由其工厂方法返回的DecimalFormat对象。For information about using Format objects, see the Formatting lesson of the Internationalization trail.有关使用Format对象的信息,请参阅国际化教程的格式化课程。

The easiest way to associate a customized format with a formatted text field is to create the field by using the JFormattedTextField constructor that takes a Format as an argument. 将自定义格式与格式化文本字段关联的最简单方法是使用JFormattedTextField构造函数创建字段,该构造函数将Format作为参数。You can see this association in the previous code examples that create amountField and rateField objects.您可以在前面创建amountFieldrateField对象的代码示例中看到这种关联。

Using 使用MaskFormatter

The MaskFormatter class implements a formatter that specifies exactly which characters are valid in each position of the field's text. MaskFormatter类实现了一个格式化程序,它精确指定字段文本的每个位置中哪些字符有效。For example, the following code creates a MaskFormatter that lets the user to type a five-digit zip code:例如,以下代码创建了一个MaskFormatter,允许用户键入五位邮政编码:

zipField = new JFormattedTextField(
                    createFormatter("
##"));
...
protected MaskFormatter createFormatter(String s) {
    MaskFormatter formatter = null;
    try {
        formatter = new MaskFormatter(s);
    } catch (java.text.ParseException exc) {
        System.err.println("formatter is bad: " + exc.getMessage());
        System.exit(-1);
    }
    return formatter;
}

You can try out the results of the preceding code by running TextInputDemo. 您可以通过运行TextInputDemo来尝试前面代码的结果。Click the Launch button to run TextInputDemo using Java™ Web Start (download JDK 7 or later). 单击启动按钮,使用Java™Web启动运行TextInputDemo(下载JDK 7或更高版本)。Alternatively, to compile and run the example yourself, consult the example index.或者,要自己编译和运行示例,请参考示例索引

Launches the TextInputDemo Application

The program's GUI is displayed.显示程序的GUI。

A snapshot of TextInputDemo

The following table shows the characters that you can use in the formatting mask:下表显示了可以在格式化掩码中使用的字符:

Character字符  Description描述
# Any valid number (Character.isDigit).任何有效数字(Character.isDigit)。
'
(single quote)
Escape character, used to escape any of the special formatting characters.转义字符,用于转义任何特殊格式字符。
U Any character (Character.isLetter). 任何字符(Character.isLetter)。All lowercase letters are mapped to uppercase.所有小写字母都映射为大写。
L Any character (Character.isLetter). 任何字符(Character.isLetter)。All uppercase letters are mapped to lowercase.所有大写字母都映射为小写。
A Any character or number (Character.isLetter or Character.isDigit).任何字符或数字(Character.isLetterCharacter.isDigit)。
? Any character (Character.isLetter).任何字符(Character.isLetter)。
* Anything.任何东西
H Any hex character (0-9, a-f or A-F).任何十六进制字符(0-9、a-f或a-f)。

Specifying Formatters and Using Formatter Factories指定格式化程序和使用格式化程序工厂

When specifying formatters, keep in mind that each formatter object can be used by at most one formatted text field at a time. 指定格式化程序时,请记住,每个格式化程序对象一次最多只能由一个格式化文本字段使用。Each field should have at least one formatter associated with it, of which exactly one is used at any time.每个字段应至少有一个与其关联的格式化程序,在任何时候都要使用其中的一个。

You can specify the formatters to be used by a formatted text field in several ways:可以通过多种方式指定格式化文本字段使用的格式化程序:

You can set a field's formatter factory either by creating the field using a constructor that takes a formatter factory argument, or by calling the setFormatterFactory method on the field. 您可以通过使用接受格式化程序工厂参数的构造函数创建字段,或通过对字段调用setFormatterFactory方法来设置字段的格式化程序工厂。To create a formatter factory, you can often use an instance of DefaultFormatterFactory class. 要创建格式化程序工厂,通常可以使用DefaultFormatterFactory类的实例。A DefaultFormatterFactory object enables you to specify the formatters returned when a value is being edited, is not being edited, or has a null value.DefaultFormatterFactory对象使您能够指定正在编辑、未编辑或具有空值时返回的格式化程序。

The following figures show an application based on the FormattedTextFieldDemo example that uses formatter factories to set multiple editors for the Loan Amount and APR fields. 下图显示了基于FormattedTextFieldDemo示例的应用程序,该示例使用格式化程序工厂为贷款金额和APR字段设置多个编辑器。While the user is editing the Loan Amount, the $ character is not used so that the user is not forced to type it. 当用户编辑贷款金额时,不使用$字符,因此用户不会被迫键入。Similarly, while the user is editing the APR field, the % character is not required.同样,当用户编辑APR字段时,不需要%字符。

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

Launches the FormatterFactoryDemo Application

FormatterFactoryDemo, with amount field being edited FormatterFactoryDemo, with no custom editors installed

The following code that creates the formatters and sets them up by using instances of the DefaultFormatterFactory class:以下代码创建了格式化程序并通过使用DefaultFormatterFactory类的实例进行设置:

private double rate = .075;  //7.5 %
...
amountField = new JFormattedTextField(
new DefaultFormatterFactory(
                        new NumberFormatter(amountDisplayFormat),
                        new NumberFormatter(amountDisplayFormat),
                        new NumberFormatter(amountEditFormat)));
...
NumberFormatter percentEditFormatter =
        new NumberFormatter(percentEditFormat) {
    public String valueToString(Object o)
          throws ParseException {
        Number number = (Number)o;
        if (number != null) {
            double d = number.doubleValue() * 100.0;
            number = new Double(d);
        }
        return super.valueToString(number);
    }
    public Object stringToValue(String s)
           throws ParseException {
        Number number = (Number)super.stringToValue(s);
        if (number != null) {
            double d = number.doubleValue() / 100.0;
            number = new Double(d);
        }
        return number;
    }
};
rateField = new JFormattedTextField(
new DefaultFormatterFactory(
                        new NumberFormatter(percentDisplayFormat),
                        new NumberFormatter(percentDisplayFormat),
                        percentEditFormatter));
...
amountDisplayFormat = NumberFormat.getCurrencyInstance();
amountDisplayFormat.setMinimumFractionDigits(0);
amountEditFormat = NumberFormat.getNumberInstance();

percentDisplayFormat = NumberFormat.getPercentInstance();
percentDisplayFormat.setMinimumFractionDigits(2);
percentEditFormat = NumberFormat.getNumberInstance();
percentEditFormat.setMinimumFractionDigits(2);

The boldface code highlights the calls to DefaultFormatterFactory constructors. 粗体代码突出显示了对DefaultFormatterFactory构造函数的调用。The first argument to the constructor specifies the default formatter to use for the formatted text field. 构造函数的第一个参数指定用于格式化文本字段的默认格式化程序。The second argument specifies the display formatter, which is used when the field does not have the focus. 第二个参数指定显示格式化程序,当字段没有焦点时使用。The third argument specifies the edit formatter, which is used when the field has the focus. 第三个参数指定编辑格式化程序,当字段具有焦点时使用。The code does not use a fourth argument, but if it did, the fourth argument would specify the null formatter, which is used when the field's value is null. 代码不使用第四个参数,但如果使用了,第四个变量将指定空格式器,当字段值为空时使用该格式器。Because no null formatter is specified, the default formatter is used when the value is null.由于未指定空格式化程序,因此当值为空时使用默认格式化程序。

The code customizes the formatter that uses percentEditFormat by creating a subclass of the NumberFormatter class. 代码通过创建NumberFormatter类的子类自定义使用percentEditFormat的格式化程序。This subclass overrides the valueToString and stringToValue methods of NumberFormatter so that they convert the displayed number to the value actually used in calculations, and convert the value to a number. 此子类重写NumberFormattervalueToStringstringToValue方法,以便它们将显示的数字转换为计算中实际使用的值,并将该值转换为数字。Specifically, the displayed number is 100 times the actual value. 具体而言,显示的数字是实际值的100倍。The reason is that the percent format used by the display formatter automatically displays the text as 100 times the value, so the corresponding editor formatter must display the text at the same value. 原因是,显示格式化程序使用的百分比格式会自动将文本显示为该值的100倍,因此相应的编辑器格式化程序必须以相同的值显示文本。The FormattedTextFieldDemo example does not need to take care of this conversion because this demo uses only one format for both display and editing.FormattedTextFieldDemo示例不需要处理此转换,因为此演示仅使用一种格式进行显示和编辑。

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

Formatted Text Field API格式化文本字段API

The following tables list some of the commonly used APIs for using formatted text fields.下表列出了使用格式化文本字段的一些常用API。

Classes Related to Formatted Text Fields与格式化文本字段相关的类
Class or Interface类或接口 Purpose目的
JFormattedTextField Subclass of JTextField that supports formatting arbitrary values.JTextField的子类,支持格式化任意值。
JFormattedTextField.AbstractFormatter The superclass of all formatters for JFormattedTextField. JFormattedTextField的所有格式化程序的超类。A formatter enforces editing policies and navigation policies, handles string-to-object conversions, and manipulates the JFormattedTextField as necessary to enforce the desired policy.格式化程序强制执行编辑策略和导航策略,处理字符串到对象的转换,并根据需要操纵JFormattedTextField以强制执行所需的策略。
JFormattedTextField.AbstractFormatterFactory The superclass of all formatter factories. 所有格式化程序工厂的超类。Each JFormattedTextField uses a formatter factory to obtain the formatter that best corresponds to the text field's state.每个JFormattedTextField都使用一个格式化程序工厂来获取与文本字段状态最对应的格式化程序。
DefaultFormatterFactory The formatter factory normally used. 通常使用的格式化程序工厂。Provides formatters based on details such as the passed-in parameters and focus state.根据传入参数和焦点状态等详细信息提供格式化程序。
DefaultFormatter Subclass of JFormattedTextField.AbstractFormatter that formats arbitrary objects by using the toString method.JFormattedTextField.AbstractFormatter的子类,通过使用toString方法格式化任意对象。
MaskFormatter Subclass of DefaultFormatter that formats and edits strings using a specified character mask. DefaultFormatter的子类,使用指定的字符掩码格式化和编辑字符串。(For example, seven-digit phone numbers can be specified by using " - #".)(例如,可以使用“ - # ”指定七位电话号码)
InternationalFormatter Subclass of DefaultFormatter that uses an instance of java.text.Format to handle conversion to and from a String.DefaultFormatter的子类,它使用java.text.Format的实例来处理与String的转换。
NumberFormatter Subclass of InternationalFormatter that supports number formats by using an instance of NumberFormat.InternationalFormatter的子类,通过使用NumberFormat实例支持数字格式。
DateFormatter Subclass of InternationalFormatter that supports date formats by using an instance of DateFormat.InternationalFormatter的子类,通过使用DateFormat的实例支持日期格式。
JFormattedTextField Methods方法
Method or Constructor方法或构造函数 Purpose目的
JFormattedTextField()
JFormattedTextField(Object)
JFormattedTextField(Format)
JFormattedTextField(AbstractFormatter)
JFormattedTextField(AbstractFormatterFactory)
JFormattedTextField(AbstractFormatterFactory, Object)
Creates a new formatted text field. 创建新的格式化文本字段。The Object argument, if present, specifies the initial value of the field and causes an appropriate formatter factory to be created. Object参数(如果存在)指定字段的初始值,并导致创建适当的格式化程序工厂。The Format or AbstractFormatter argument specifies the format or formatter to be used for the field, and causes an appropriate formatter factory to be created. FormatAbstractFormatter参数指定字段要使用的格式或格式化程序,并导致创建适当的格式化程序工厂。The AbstractFormatterFactory argument specifies the formatter factory to be used, which determines which formatters are used for the field.AbstractFormatterFactory参数指定要使用的格式化程序工厂,它确定字段使用哪些格式化程序。
void setValue(Object)
Object getValue()
Sets or obtains the value of the formatted text field. 设置或获取格式化文本字段的值。You must cast the return type based on how the JFormattedTextField has been configured. 必须根据JFormattedTextField的配置方式强制转换返回类型。If the formatter has not been set yet, calling setValue sets the formatter to one returned by the field's formatter factory.如果尚未设置格式化程序,则调用setValue将格式化程序设置为字段的格式化程序工厂返回的格式化程序。
void setFormatterFactory(AbstractFormatterFactory) Sets the object that determines the formatters used for the formatted text field. 设置确定用于格式化文本字段的格式化程序的对象。The object is often an instance of the DefaultFormatterFactory class.该对象通常是DefaultFormatterFactory类的实例。
AbstractFormatter getFormatter() Obtains the formatter of the formatted text field. 获取格式化文本字段的格式化程序。The formatter is often an instance of the DefaultFormatter class.格式化程序通常是DefaultFormatter类的实例。
void setFocusLostBehavior(int) Specifies the outcome of a field losing the focus. 指定字段失去焦点的结果。Possible values are defined in JFormattedTextField as COMMIT_OR_REVERT (the default), COMMIT (commit if valid, otherwise leave everything the same), PERSIST (do nothing), and REVERT (change the text to reflect the value).可能的值在JFormattedTextField中定义为COMMIT_OR_REVERT(默认值)、COMMIT(如果有效则提交,否则保持所有内容不变)、PERSIST(不执行任何操作)和REVERT(更改文本以反映值)。
void commitEdit() Sets the value to the object represented by the field's text, as determined by the field's formatter. 将值设置为字段文本表示的对象,由字段的格式化程序确定。If the text is invalid, the value remains the same and a ParseException is thrown.如果文本无效,则值保持不变,并引发ParseException
boolean isEditValid() Returns true if the formatter considers the current text to be valid, as determined by the field's formatter.如果格式化程序认为当前文本有效(由字段的格式化程序确定),则返回true
DefaultFormatter Options选项
Method方法 Purpose目的
void setCommitsOnValidEdit(boolean)
boolean getCommitsOnValidEdit()
Sets or obtains values when edits are pushed back to the JFormattedTextField. 设置或获取将编辑推回JFormattedTextField时的值。If true, commitEdit is called after every valid edit. 如果为true,则在每次有效编辑后调用CommittedItThis property is false by default.默认情况下,此属性为false
void setOverwriteMode(boolean)
boolean getOverwriteMode()
Sets or obtains the behavior when inserting characters. 设置或获取插入字符时的行为。If true, new characters overwrite existing characters in the model as they are inserted. 如果为true,则新字符将在插入时覆盖模型中的现有字符。The default value of this property is true in DefaultFormatter (and thus in MaskFormatter) and false in InternationalFormatter (and thus in DateFormatter and NumberFormatter).此属性的默认值在DefaultFormatter(因此在MaskFormatter中)中为true,在InternationalFormattor(因此在DateFormatterNumberFormatter)中为false
void setAllowsInvalid(boolean)
boolean getAllowsInvalid()
Sets or interprets whether the value being edited is allowed to be invalid for a length of time. 设置或解释正在编辑的值是否允许在一段时间内无效。It is often convenient to enable the user to type invalid values until the commitEdit method is attempted. 在尝试CommittedIt方法之前,允许用户键入无效值通常是很方便的。DefaultFormatter initializes this property to true. DefaultFormatter将此属性初始化为trueOf the standard Swing formatters, only MaskFormatter sets this property to false.在标准Swing格式化程序中,只有MaskFormatter将此属性设置为false

Examples That Use Formatted Text Fields使用格式化文本字段的示例

This table lists examples that use formatted text fields and points to where those examples are described.下表列出了使用格式化文本字段的示例,并指出了这些示例的描述位置。

Example示例 Where Described描述位置 Notes备注
FormattedTextFieldDemo This section本节 Uses four formatted text fields.使用四个格式化文本字段。
SpinnerDemo How to Use Spinners如何使用微调器 Customizes the appearance of the formatted text fields used by two spinners.自定义两个微调器使用的格式化文本字段的外观。
Converter Using Models使用模型 Each ConversionPanel pairs a formatted text field with a slider.每个ConversionPanel将格式化的文本字段与滑块配对。
TextInputDemo This section本节 Shows how to use text fields, spinners, and formatted text fields together, and demonstrates how to use MaskFormatter. 演示如何同时使用文本字段、微调器和格式化文本字段,并演示如何使用MaskFormatterIncludes code for selecting the text of the field that has just received the focus.包括用于选择刚刚接收到焦点的字段文本的代码。
FormatterFactoryDemo This section本节 A variation on FormattedTextFieldDemo that uses formatter factories to specify multiple formatters for two formatted text fields.FormattedTextFieldDemo的一个变体,它使用格式化程序工厂为两个格式化文本字段指定多个格式化程序。

Previous page: How to Use File Choosers
Next page: How to Make Frames (Main Windows)