📄 formattedtextfield.html
字号:
you can set up formatted text fieldsfor easy input of dates and numbersin localized formats.Another kind of formatterlets you use a character maskto specify the set of charactersthat can be entered at each position in the field.For example, you can specify a maskfor entering phone numbers in a particular format,such as (XX) X-XX-XX-XX-XX.<p>If the possible values of a formatted text field have anobvious order,consider using a <a href="spinner.html">spinner</a> instead.A spinner uses a formatted text field,by default,but adds two buttons that let the userstep through a sequence of values.<p>Another alternative or adjunct to using a formatted text fieldis installing an<a class="TutorialLink" target="_top" href="../misc/focus.html#inputVerification">input verifier</a> on the field.A component's input verifier is calledwhen the component is about to lose the keyboard focus.It lets youcheck whether the value of the component is legaland optionally change it orstop focus from being transferred.<p>Here is a picture of a GUI that uses formatted text fieldsto display numbers in four different formats.<p><center><IMG SRC="../../figures/uiswing/components/FormattedTextFieldDemoMetal.png" WIDTH="265" HEIGHT="154" ALIGN="BOTTOM" ALT="A snapshot of FormattedTextFieldDemo"></center></p><blockquote><hr><strong>Try this:</strong> <ol><li> <a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/FormattedTextFieldDemo.jnlp">Run FormattedTextFieldDemo</a> (it requires release 6) using<a class="TutorialLink" target="_top" href="../../information/javawebstart.html">Java<sup><font size=-2>TM</font></sup> Web Start</a>. Or, to compile and run the example yourself, consult the <a href="examples/index.html#FormattedTextFieldDemo">example index</a>.<li> Experiment with different loan amounts, annual percentage rates (APR), and loan lengths.<br> Note that the Month Payment field is updated when you either press Enter or move the focus out of the field you're editing, as long as the text you type is valid.<li> Enter invalid text such as "abcd" in the Loan Amount field and then press Enter. <br> Nothing happens. When you move the focus from the field, the text reverts to the field's last valid value.<li> Enter marginally valid text such as "2000abcd" in the Loan Amount field and press Enter. <br> The Monthly Payment field is updated, though the Loan Amount field still looks strange. When you move the focus from the Loan Amount field, the text it displays is updated to be a nicely formatted version of its value — for example, "2,000".</ol><hr></blockquote>You can find the full code in<a class="SourceLink" target="_blank" href="examples/FormattedTextFieldDemo.java"><code><code>FormattedTextFieldDemo.java</code></code></a>.Here is the code that creates the first field:<blockquote><pre>amountField = new JFormattedTextField(amountFormat);amountField.setValue(new Double(amount));amountField.setColumns(10);amountField.addPropertyChangeListener("value", this);...amountFormat = NumberFormat.getNumberInstance();</pre></blockquote><p>The constructor used to create <code>amountField</code>takes a <code>java.text.Format</code> argument.The <code>Format</code> object is used by the field's formatterto translate between the field's text and value.<p>The rest of the codesets up <code>amountField</code>.The <code>setValue</code> method sets the field'svalue property to a floating point numberrepresented as a <code>Double</code> object.The <code>setColumns</code> method,inherited from <code>JTextField</code>,provides a hint as to the preferred size of the field.Finally, the call to <code>addPropertyChangeListener</code>registers a listenerfor the value property of the field,so the program can update the Monthly Payment fieldwhenever the user changes the loan amount.<p>The rest of this section covers the following topics:<ul><li> <a href="#constructors">Creating and Initializing Formatted Text Fields</a><li> <a href="#value">Setting and Getting the Field's Value</a><li> <a href="#format">Specifying Formats</a><li> <a href="#maskformatter">Using MaskFormatter</a><li> <a href="#factory">Specifying Formatters and Using Formatter Factories</a></ul><p>This section doesn't explain the API inherited from<code>JTextField</code>.That API is described in<a href="textfield.html">How to Use Text Fields</a>.</blockquote><h3><a name="constructors">Creating and Initializing Formatted Text Fields</a></h3><blockquote><p>The following code creates and initializes the remaining three fieldsin FormattedTextFieldDemo.<blockquote><pre>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();</pre></blockquote><p>The code for setting up <code>rateField</code>is almost identical to the code you saw before.The only difference is that the format is slightly different,thanks to the code <code>percentFormat.setMinimumFractionDigits(2)</code>.<p>The codethat creates <code>numPeriodsField</code>doesn't explicitly set a format or formatter.Instead, it sets the value to an <code>Integer</code>and lets the field use the default formatter for <code>Integer</code>s.We couldn't do this in the previous two fieldsbecause we didn't want to use the default formatterfor <code>Double</code>s;the result didn't look exactly like we wanted it to.We'll discuss how to specify formats and formattersa little later.<p>The payment field is different from theother fields because it's uneditable,uses a different color for its text,and doesn't happen to have a property change listener.However, it's otherwise the sameas the other fields.We could have chosen to use a<a href="textfield.html">text field</a> or<a href="label.html">label</a> instead.Whatever the component,we could still use <code>paymentFormat</code> to parse thepayment amount into the text to be displayed.</blockquote><h3><a name="value">Setting and Getting the Field's Value</a></h3><blockquote><p>Keep this in mindwhen using a formatted text field:<blockquote><hr><strong>A formatted text field's <em>text</em>and its <em>value</em>are two different properties,and the value often lags the text.</strong><hr></blockquote><p>The <em>text</em> property is defined by <code>JTextField</code>;it always reflects what the field displays.The <em>value</em> property, defined by <code>JFormattedTextField</code>,might not reflect the latest text displayed in the field.While the user is typing,the text property changes,but the value property doesn'tuntil the changes are <em>committed</em>.<p>To be more precise,the value of a formatted text field can be setusing either the <code>setValue</code> methodor the <code>commitEdit</code> method.The <code>setValue</code> method sets the valueto the specified argument.Although the argument can technically be any <code>Object</code>,it needs to be something that the formatter canconvert into a string.Otherwise, the text field won't display anything useful.<p>The <code>commitEdit</code> methodsets the value to whatever objectthe formatter determines is represented by the field's text.The <code>commitEdit</code> method isautomatically called when either of the following happens:<ul><li> When the user presses Enter while the field has the focus.<li> By default, when the field loses the focus — for example, the user presses Tab to change the focus to another component. You can use the <code>setFocusLostBehavior</code> method to specify that something different should happen when the field loses the focus.</ul><blockquote><hr><strong>Note:</strong> Some formatters might update the value constantly,making the focus-lost behavior mootsince the value will always be the same as what the text specifies.<hr></blockquote><p>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 textdepends on the field's formatter.<p>Note that although <code>JFormattedTextField</code>inherits the <code>setText</code> method from<code>JTextField</code>,you don't usually invoke <code>setText</code> on a formatted text field.If you do,the field's display will change accordinglybut the value will not be updated(unless the field's formatter updates it constantly).<p>To get a formatted text field's current value,use the <code>getValue</code> method.If necessary, you can ensure the value reflects the textby calling <code>commitEdit</code>before <code>getValue</code>.Because <code>getValue</code> returns an <code>Object</code>,you need to cast it to the type used for your field's value.For example:<blockquote><pre>Date enteredDate = (Date)dateField.getValue();</pre></blockquote><p>To detect changes in a formatted text field's value,you can register a property change listeneron the formatted text fieldto listen for changes to the "value" property.Here is the property change listener from FormattedTextFieldDemo:<blockquote><pre><em>//The property change listener is registered on each//field using code like this:// someField.addPropertyChangeListener("value", this);</em>/** 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));}</pre></blockquote></blockquote><h3><a name="format">Specifying Formats</a></h3><blockquote>The<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/text/Format.html"><code>Format</code></a> class provides a way to formatlocale-sensitive information such as dates and numbers.Formatters that descend from<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/text/InternationalFormatter.html"><code>InternationalFormatter</code></a>, such as<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/text/DateFormatter.html"><code>DateFormatter</code></a> and<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/text/NumberFormatter.html"><code>NumberFormatter</code></a>, use <code>Format</code> objectsto translate between the field's text and value.You can get a <code>Format</code> objectby invoking one of the factory methods in<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/text/DateFormat.html"><code>DateFormat</code></a> or<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/text/NumberFormat.html"><code>NumberFormat</code></a>, or by using one of the<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html"><code>SimpleDateFormat</code></a> constructors.<blockquote><hr><strong>Note:</strong> A third commonly used formatter class,<code>MaskFormatter</code>,does not descend from <code>InternationalFormatter</code>and does not use formats.It's discussed in<a href="#maskformatter">Using MaskFormatter</a>.<hr></blockquote><p>You can customize certain format aspectswhen you create the <code>Format</code>,and others through format-specific API.For example,<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/text/DecimalFormat.html"><code>DecimalFormat</code></a> objects,which inherit from <code>NumberFormat</code>and are often returned by its factory methods,can be customized using the<code>setMaximumFractionDigits</code> and<code>setNegativePrefix</code> methods.For information about using <code>Format</code>s,see the<a class="TutorialLink" target="_top" href="../../i18n/format/index.html">Formatting</a> lesson of the Internationalization trail.<p>The easiest way to associate a customized format
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -