⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 formattedtextfield.html

📁 jsf、swing的官方指南
💻 HTML
📖 第 1 页 / 共 4 页
字号:
with a formatted text fieldis to create the field usingthe <code>JFormattedTextField</code> constructorthat takes a <code>Format</code> as an argument.You can see this in the previous code snippets that create<code>amountField</code> and <code>rateField</code>.</blockquote><a name="maskformatter"><h3>Using MaskFormatter</h3></a><blockquote>The<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/text/MaskFormatter.html"><code>MaskFormatter</code></a> class implements a formatterthat specifies exactly which characters arelegal in each position of the field's text.For example, the following code creates a <code>MaskFormatter</code>that lets the user enter a 5-digit zip code:<blockquote><pre>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;}</pre></blockquote>You can try out the results of the preceding code by<a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/TextInputDemo.jnlp">running TextInputDemo</a> (it requires release 6)using<a class="TutorialLink" target="_top" href="../../information/javawebstart.html">Java Web Start</a>.    Or, to compile and run the example yourself,     consult the     <a href="examples/index.html#TextInputDemo">example index</a>.Here is a picture of the program's GUI:<p><center><IMG SRC="../../figures/uiswing/components/TextInputDemoMetal.png" WIDTH="549" HEIGHT="185" ALIGN="BOTTOM" ALT="A snapshot of TextInputDemo"></center></p><p>The following table showsthe characters you can use in the formatting mask:<p><table border=1 summary="Valid characters and their descriptions"><tr>   <th align=center>Character&nbsp;</th>   <th align=left>Description</th></tr><tr>   <td align=center>#</td>   <td>Any valid number (<code>Character.isDigit</code>).</td></tr><tr>   <td align=center>'   <br>   <em>(single quote)</em></td>   <td>Escape character, used to escape any of the      special formatting characters.</td></tr><tr>   <td align=center>U</td>   <td>Any character (<code>Character.isLetter</code>). All       lowercase letters are mapped to uppercase.</td></tr><tr><td align=center>L</td>    <td>Any character (<code>Character.isLetter</code>). All       uppercase letters are mapped to lowercase.</td></tr><tr><td align=center>A</td>    <td>Any character or number (<code>Character.isLetter</code>      or <code>Character.isDigit</code>).</td></tr><tr><td align=center>?</td>    <td>Any character       (<code>Character.isLetter</code>).</td></tr><tr><td align=center>*</td>    <td>Anything.</td></tr><tr><td align=center>H</td>    <td>Any hex character (0-9, a-f or A-F).</td></tr></table></blockquote><h3><a name="factory">Specifying Formatters and Using Formatter Factories</a></h3><blockquote>When specifying formatters,keep in mind that each formatter objectcan be used by at most oneformatted 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.<p>You can specify the formatters to be used by a formatted text fieldin several ways:<ul><li><b>Use the <code>JFormattedTextField</code> constructorthat takes a <code>Format</code> argument.</b><br>A formatter for the field is automatically createdthat uses the specified format.<p><li><b>Use the <code>JFormattedTextField</code> constructorthat takes a <code>JFormattedTextField.AbstractFormatter</code> argument.</b><br>The specified formatter is used for the field.<p><li><b>Set the value of a formatted text fieldthat has no format, formatter, or formatter factory specified.</b><br>A formatter is assigned to the field by the default formatter factory,using the type of the field's value as a guide.If the value is a <code>Date</code>,the formatter is a <code>DateFormatter</code>.If the value is a <code>Number</code>,the formatter is a <code>NumberFormatter</code>.Other typesresult in an instance of <code>DefaultFormatter</code>.<p><li><b>Make the formatted text field usea formatter factory that returns customized formatter objects.</b><br>This is the most flexible approach.It's useful when you want to associatemore than one formatter with a fieldor add a new kind of formatterto be used for multiple fields.As an example of the former use,you might have a field that shouldinterpret user typing a certain waybut display the value (when the user isn't typing) another way.As an example of the latter use,you might have several fieldsthat have values of a custom class &#151;say, <code>PhoneNumber</code>.You could set up the fields to use a formatter factorythat can return specialized formatters for phone numbers.</ul><p>You can set a field's formatter factoryeither by creating the field using a constructorthat takes a formatter factory argument,or by invoking the <code>setFormatterFactory</code> methodon the field.To create a formatter factory,you can often use an instance of<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/text/DefaultFormatterFactory.html"><code>DefaultFormatterFactory</code></a>.A <code>DefaultFormatterFactory</code> objectlets you specify the formatters returnedwhen a value is being edited, not being edited,or has a null value.<p>The following pictures show an applicationbased on FormattedTextFieldDemothat uses formatter factoriesto set multiple editors for theLoan Amount and APR fields.While the user is editing the Loan Amount,the $ character is not usedso that the user isn't forced to enter it.Similarly, while the user is editing the APR field,the % is not required.You can<a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/FormatterFactoryDemo.jnlp">run the example</a> (it requires release 6)using<a class="TutorialLink" target="_top" href="../../information/javawebstart.html">Java Web Start</a>.    Or, to compile and run the example yourself,     consult the     <a href="examples/index.html#FormatterFactoryDemo">example index</a>.<p align=center><IMG SRC="../../figures/uiswing/components/FormatterFactoryDemoMetal.png" WIDTH="260" HEIGHT="154" ALT="FormatterFactoryDemo, with amount field being edited"><IMG SRC="../../figures/uiswing/components/FormatterFactoryDemo2Metal.png" WIDTH="260" HEIGHT="154" ALT="FormatterFactoryDemo, with no custom editors installed"><p>Here is the code that creates the formattersand sets them up,using instances of <code>DefaultFormatterFactory</code>:<blockquote><pre>private double rate = .075;  //7.5 %...amountField = new JFormattedTextField(                    <b>new DefaultFormatterFactory(                        new NumberFormatter(amountDisplayFormat),                        new NumberFormatter(amountDisplayFormat),                        new NumberFormatter(amountEditFormat))</b>);...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(                     <b>new DefaultFormatterFactory(                        new NumberFormatter(percentDisplayFormat),                        new NumberFormatter(percentDisplayFormat),                        percentEditFormatter)</b>);...amountDisplayFormat = NumberFormat.getCurrencyInstance();amountDisplayFormat.setMinimumFractionDigits(0);amountEditFormat = NumberFormat.getNumberInstance();percentDisplayFormat = NumberFormat.getPercentInstance();percentDisplayFormat.setMinimumFractionDigits(2);percentEditFormat = NumberFormat.getNumberInstance();percentEditFormat.setMinimumFractionDigits(2);</pre></blockquote>The boldface code highlights the calls to<code>DefaultFormatterFactory</code> constructors.The first argument to the constructor specifies the default formatterto use for the formatted text field.The second specifies the display formatter,which is usedwhen the field doesn't have the focus.The third specifies the edit formatter,used when the field has the focus.The code doesn't use a fourth argument,but if it did,it 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.<p>The code customizes the formatterthat uses <code>percentEditFormat</code>by creating a subclass of <code>NumberFormatter</code>.This subclass overrides the <code>valueToString</code>and <code>stringToValue</code> methodsof <code>NumberFormatter</code>so that they convert the displayed numberto the value actually used in calculations,and vice versa.Specifically, the displayed numberis 100 times the actual value.The reason is that the percent formatused by the display formatterautomatically displays the textas 100 times the value,so the corresponding editor formatter must do so as well.FormattedTextFieldDemo doesn't need to worry about this conversionbecause it uses only one format for both display and editing.<p>You can find the code for the entire program in<a class="SourceLink" target="_blank" href="examples/FormatterFactoryDemo.java"><code><code>FormatterFactoryDemo.java</code></code></a>.</blockquote><h3><a name="api">The Formatted Text Field API</a></h3><blockquote>The following tables list some of the commonly used APIfor using formatted text fields.<ul><li><a href="#newclassesapi">Classes Related to Formatted Text Fields</a><li><a href="#formattedtextfieldapi">JFormattedTextField Methods</a><li><a href="#defaultformatterapi">DefaultFormatter Options</a></ul><p><table border=1><caption><a name="newclassesapi">Classes Related to Formatted Text Fields</a></caption><tr><th align=left>Class or Interface</th><th align=left>Purpose</th></tr>  <tr>    <td><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JFormattedTextField.html">JFormattedTextField</a>    </td>    <td>Subclass of <code>JTextField</code>        that supports formatting arbitrary values.    </td>  </tr>  <tr>    <td><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JFormattedTextField.AbstractFormatter.html">JFormattedTextField.AbstractFormatter</a>  <td>     The superclass of all formatters for <code>JFormattedTextField</code>.     A formatter enforces editing policies and navigation policies,     handles string-to-object conversions,     and manipulates the <code>JFormattedTextField</code> as     necessary to enforce the desired policy.  </tr>  <tr>    <td><a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JFormattedTextField.AbstractFormatterFactory.html">JFormattedTextField.AbstractFormatterFactory</a>    </td>    <td>The superclass of all formatter factories.    Each <code>JFormattedTextField</code> uses a formatter factory    to obtain the formatter that best corresponds to the text field's state.    </td>  </tr>  <tr>    <td>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -