How to Read Value of a Number From a Jtextfield
Formatted text fields provide a mode 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
form. The formatter translates the field'south value into the text it displays, and the text into the field'southward value.
Using the formatters that Swing provides, you can gear up formatted text fields to blazon dates and numbers in localized formats. Another kind of formatter enables you to employ a character mask to specify the prepare of characters that can be typed at each position in the field. For example, you can specify a mask for typing telephone numbers in a particular format, such every bit (XX) Ten-XX-XX-XX-XX.
If the possible values of a formatted text field have an obvious order, apply a spinner instead. A spinner uses a formatted text field by default, but adds 2 buttons that enable the user to choose a value in a sequence.
Some other culling or adjunct to using a formatted text field is installing an input verifier on the field. A component's input verifier is chosen when the component well-nigh loses the keyboard focus. The input verifier enables you lot to cheque whether the value of the component is valid and optionally modify it or stop the focus from being transferred.
This GUI uses formatted text fields to display numbers in four different formats.
Try this:
- Click the Launch push to run FormattedTextFieldDemo using Java™ Web Commencement (download JDK vii or later). Alternatively, to compile and run the example yourself, consult the case alphabetize.
- Experiment with dissimilar loan amounts, annual pct rates (APRs), and loan lengths.
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. - Blazon invalid text such as "abcd" in the Loan Amount field and and so press Enter.
The Calendar month Payment field remains the same. When you motion the focus from the Loan Corporeality field, the text reverts to the field'southward last valid value. - Blazon marginally valid text such as "2000abcd" in the Loan Corporeality field and press Enter.
The Monthly Payment field is updated, though the Loan Corporeality field still displays2000abcd
. When yous move the focus from the Loan Corporeality field, the text information technology displays is updated to a neatly formatted version of its value, for example, "ii,000".
You lot can find the entire code for this program in
. This code creates the first field.FormattedTextFieldDemo.java
amountField = new JFormattedTextField(amountFormat); amountField.setValue(new Double(amount)); amountField.setColumns(ten); amountField.addPropertyChangeListener("value", this); ... amountFormat = NumberFormat.getNumberInstance();
The constructor used to create the amountField
object takes a java.text.Format
argument. The Format
object is used by the field's formatter to interpret the field'due south value to text and the text to the field's value.
The remaining code sets upwardly the amountField
object. The setValue
method sets the field's value property to a floating-point number represented as a Double
object. The setColumns
method, inherited from the JTextField
class, hints virtually the preferred size of the field. The call to the addPropertyChangeListener
method registers a listener for the value property of the field, and so the programme can update the Monthly Payment field whenever the user changes the loan amount.
The balance of this section covers the following topics:
- Creating and Initializing Formatted Text Fields
- Setting and Getting the Field's Value
- Specifying Formats
- Using MaskFormatter
- Specifying Formatters and Using Formatter Factories
This section does non explain the API inherited from the JTextField
course. That API is described in How to Use Text Fields.
Creating and Initializing Formatted Text Fields
The following code creates and initializes the remaining three fields in the FormattedTextFieldDemo
example.
rateField = new JFormattedTextField(percentFormat); rateField.setValue(new Double(rate)); rateField.setColumns(x); rateField.addPropertyChangeListener("value", this); numPeriodsField = new JFormattedTextField(); numPeriodsField.setValue(new Integer(numPeriods)); numPeriodsField.setColumns(x); numPeriodsField.addPropertyChangeListener("value", this); paymentField = new JFormattedTextField(paymentFormat); paymentField.setValue(new Double(payment)); paymentField.setColumns(10); paymentField.setEditable(fake); paymentField.setForeground(Color.red); ... percentFormat = NumberFormat.getNumberInstance(); percentFormat.setMinimumFractionDigits(ii); paymentFormat = NumberFormat.getCurrencyInstance();
The code for setting up the rateField
object is almost identical to the code listed previously for other fields. The only departure is that the format is slightly dissimilar, thank you to the code percentFormat.setMinimumFractionDigits(2)
.
The code that creates the numPeriodsField
object does non explicitly prepare a format or formatter. Instead, it sets the value to an Integer
and enables the field to utilize the default formatter for Integer
objects. The code did not practice this in the previous ii fields because the default formatter is non being used for Double
objects. The effect was non what was needed. How to specify formats and formatters is covered later on in this section.
The payment field is different from the other fields considering it is uneditable, uses a unlike color for its text, and does not have a property change listener. Otherwise, it is identical to the other fields. We could accept chosen to use a text field or label instead. Whatever the component, we could however use the paymentFormat
method to parse the payment amount into the text to be displayed.
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 dissimilar properties, and the value frequently lags backside the text.
The text property is defined by the JTextField
grade. This property always reflects what the field displays. The value property, defined by the JFormattedTextField
class, might non reverberate the latest text displayed in the field. While the user is typing, the text belongings changes, but the value property does not change until the changes are committed.
To be more precise, the value of a formatted text field tin can exist set by using either the setValue
method or the commitEdit
method. The setValue
method sets the value to the specified statement. The argument can technically exist any Object
, but the formatter needs to be able to catechumen information technology into a string. Otherwise, the text field does not brandish any substantive information.
The commitEdit
method sets the value to whatever object the formatter determines is represented past the field's text. The commitEdit
method is automatically called when either of the post-obit happens:
- When the user presses Enter while the field has the focus.
- By default, when the field loses the focus, for example, when the user presses the Tab key to alter the focus to another component. You tin use the
setFocusLostBehavior
method to specify a different event when the field loses the focus.
Note:
Some formatters might update the value constantly, rendering the loss of focus meaningless, as the value is always the same equally what the text specifies.
When you ready 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
form inherits the setText
method from the JTextField
course, you do not usually call the setText
method on a formatted text field. If you do, the field's display changes accordingly but the value is non updated (unless the field's formatter updates information technology constantly).
To obtain a formatted text field'due south current value, use the getValue
method. If necessary, you tin ensure that the value reflects the text by calling the commitEdit
method before getValue
. Because the getValue
method returns an Object
, yous need to cast it to the type used for your field'due south value. For instance:
Date enteredDate = (Engagement)dateField.getValue();
To detect changes in a formatted text field's value, yous tin can register a property change listener on the formatted text field to heed for changes to the "value" property. The holding change listener is taken from the FormattedTextFieldDemo
example:
//The property change listener is registered on each //field using code similar this: // someField.addPropertyChangeListener("value", this); /** Chosen when a field's "value" property changes. */ public void propertyChange(PropertyChangeEvent east) { 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 fashion to format locale-sensitive data such as dates and numbers. Formatters that descend from the InternationalFormatter
class, such as the DateFormatter
and NumberFormatter
classes, apply Format
objects to translate between the field's text and value. You can obtain a Format
object by calling one of the manufactory methods in the DateFormat
or NumberFormat
classes, or by using one of the SimpleDateFormat
constructors.
Note:
A tertiary unremarkably used formatter class, MaskFormatter
, does not descend from the InternationalFormatter
grade and does non use formats. The MaskFormatter
is discussed in Using MaskFormatter.
Yous can customize sure format aspects when you create the Format
object, and others through a format-specific API. For case, DecimalFormat
objects, which inherit from NumberFormat
and are often returned by its factory methods, can exist customized by using the setMaximumFractionDigits
and setNegativePrefix
methods. For information about using Format
objects, see the Formatting lesson of the Internationalization trail.
The easiest style 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 statement. You can see this clan in the previous lawmaking examples that create amountField
and rateField
objects.
Using MaskFormatter
The MaskFormatter
class implements a formatter that specifies exactly which characters are valid in each position of the field's text. For instance, the following code creates a MaskFormatter
that lets the user to type a 5-digit zip code:
zipField = new JFormattedTextField( createFormatter("#####")); ... protected MaskFormatter createFormatter(String s) { MaskFormatter formatter = nada; attempt { formatter = new MaskFormatter(s); } grab (java.text.ParseException exc) { Organization.err.println("formatter is bad: " + exc.getMessage()); System.get out(-ane); } render formatter; }
You can try out the results of the preceding code past running TextInputDemo
. Click the Launch button to run TextInputDemo using Coffee™ Web Start (download JDK seven or after). Alternatively, to compile and run the example yourself, consult the example index.
The program's GUI is displayed.
The post-obit tabular array shows the characters that you lot tin can use in the formatting mask:
Character | Description |
---|---|
# | Any valid number (Character.isDigit ). |
' (single quote) | Escape grapheme, used to escape any of the special formatting characters. |
U | Any graphic symbol (Character.isLetter ). All lowercase letters are mapped to uppercase. |
50 | Any grapheme (Graphic symbol.isLetter ). All uppercase messages are mapped to lowercase. |
A | Whatsoever character or number (Character.isLetter or Character.isDigit ). |
? | Any character (Graphic symbol.isLetter ). |
* | Anything. |
H | Any hex character (0-ix, a-f or A-F). |
Specifying Formatters and Using Formatter Factories
When specifying formatters, keep in listen that each formatter object can be used by at most one formatted text field at a time. Each field should accept at least one formatter associated with information technology, of which exactly ane is used at whatsoever fourth dimension.
Yous can specify the formatters to be used past a formatted text field in several means:
- Use the
JFormattedTextField
constructor that takes aFormat
argument.
A formatter for the field is automatically created that uses the specified format. - Use the
JFormattedTextField
constructor that takes aJFormattedTextField.AbstractFormatter
argument.
The specified formatter is used for the field. - Set the value of a formatted text field that has no format, formatter, or formatter manufactory specified.
A formatter is assigned to the field past the default formatter factory, using the type of the field'due south value equally a guide. If the value is aAppointment
, the formatter is aDateFormatter
. If the value is aNumber
, the formatter is aNumberFormatter
. Other types result in an instance ofDefaultFormatter
. - Make the formatted text field use a formatter manufactory that returns customized formatter objects.
This is the most flexible arroyo. It is useful when you lot want to associate more than one formatter with a field or add together a new kind of formatter to be used for multiple fields. An case of the former employ is a field that interprets the user typing in a certain way but displays the value (when the user is not typing) in another mode. An instance of the latter use is several fields with custom class values, for example,PhoneNumber
. You tin set up the fields to use a formatter factory that returns specialized formatters for telephone numbers.
You can set a field's formatter mill either by creating the field using a constructor that takes a formatter manufactory argument, or by calling the setFormatterFactory
method on the field. To create a formatter factory, you tin can often use an case of DefaultFormatterFactory
class. A DefaultFormatterFactory
object enables you to specify the formatters returned when a value is existence edited, is not beingness edited, or has a nada value.
The following figures prove an awarding based on the FormattedTextFieldDemo
example that uses formatter factories to ready multiple editors for the Loan Corporeality and Apr fields. While the user is editing the Loan Amount, the $ character is not used so that the user is not forced to blazon it. Similarly, while the user is editing the APR field, the % character is not required.
Click the Launch button to run FormatterFactoryDemo using Java™ Spider web Commencement (download JDK 7 or afterwards). Alternatively, to compile and run the example yourself, consult the case alphabetize.
The following code that creates the formatters and sets them upward by using instances of the DefaultFormatterFactory
grade:
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(Cord s) throws ParseException { Number number = (Number)super.stringToValue(due south); if (number != null) { double d = number.doubleValue() / 100.0; number = new Double(d); } render 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 lawmaking highlights the calls to DefaultFormatterFactory
constructors. The first argument to the constructor specifies the default formatter to use for the formatted text field. The 2nd argument specifies the brandish formatter, which is used when the field does not have the focus. The 3rd statement specifies the edit formatter, which is used when the field has the focus. The lawmaking does not use a 4th statement, but if it did, the quaternary argument would specify the null formatter, which is used when the field's value is nil. Because no null formatter is specified, the default formatter is used when the value is null.
The lawmaking customizes the formatter that uses percentEditFormat
by creating a subclass of the NumberFormatter
class. This subclass overrides the valueToString
and stringToValue
methods of NumberFormatter
then that they catechumen the displayed number to the value actually used in calculations, and catechumen the value to a number. Specifically, the displayed number is 100 times the bodily value. The reason is that the percent format used past the brandish formatter automatically displays the text equally 100 times the value, so the respective editor formatter must brandish the text at the same value. The FormattedTextFieldDemo
example does not need to take care of this conversion because this demo uses just one format for both brandish and editing.
Y'all can notice the code for the entire program in
.FormatterFactoryDemo.java
Formatted Text Field API
The following tables list some of the commonly used APIs for using formatted text fields.
- Classes Related to Formatted Text Fields
- JFormattedTextField Methods
- DefaultFormatter Options
Class or Interface | Purpose |
---|---|
JFormattedTextField | Bracket of JTextField that supports formatting arbitrary values. |
JFormattedTextField.AbstractFormatter | The superclass of all formatters for 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.AbstractFormatterFactory | The superclass of all formatter factories. Each JFormattedTextField uses a formatter mill to obtain the formatter that all-time corresponds to the text field'south state. |
DefaultFormatterFactory | The formatter factory normally used. Provides formatters based on details such every bit the passed-in parameters and focus state. |
DefaultFormatter | Subclass of JFormattedTextField.AbstractFormatter that formats arbitrary objects by using the toString method. |
MaskFormatter | Bracket of DefaultFormatter that formats and edits strings using a specified character mask. (For example, seven-digit phone numbers tin can be specified by using "###-####".) |
InternationalFormatter | Subclass of DefaultFormatter that uses an instance of coffee.text.Format to handle conversion to and from a Cord . |
NumberFormatter | Bracket of InternationalFormatter that supports number formats by using an case of NumberFormat . |
DateFormatter | Subclass of InternationalFormatter that supports date formats by using an instance of DateFormat . |
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 manufactory to be created. 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. The AbstractFormatterFactory argument specifies the formatter manufacturing plant to be used, which determines which formatters are used for the field. |
void setValue(Object) Object getValue() | Sets or obtains the value of the formatted text field. Yous must cast the return type based on how the JFormattedTextField has been configured. If the formatter has not been set yet, calling setValue sets the formatter to one returned by the field'south formatter factory. |
void setFormatterFactory(AbstractFormatterFactory) | Sets the object that determines the formatters used for the formatted text field. The object is ofttimes an case of the DefaultFormatterFactory class. |
AbstractFormatter getFormatter() | Obtains the formatter of the formatted text field. The formatter is oftentimes an example of the DefaultFormatter class. |
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 (exercise nothing), and REVERT (change the text to reflect the value). |
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. |
boolean isEditValid() | Returns true if the formatter considers the current text to be valid, equally determined by the field'southward formatter. |
Method | Purpose |
---|---|
void setCommitsOnValidEdit(boolean) boolean getCommitsOnValidEdit() | Sets or obtains values when edits are pushed dorsum to the JFormattedTextField . If true , commitEdit is called afterwards every valid edit. This property is simulated by default. |
void setOverwriteMode(boolean) boolean getOverwriteMode() | Sets or obtains the beliefs when inserting characters. If true , new characters overwrite existing characters in the model as they are inserted. The default value of this holding is truthful in DefaultFormatter (and thus in MaskFormatter ) and false in InternationalFormatter (and thus in DateFormatter and NumberFormatter ). |
void setAllowsInvalid(boolean) boolean getAllowsInvalid() | Sets or interprets whether the value beingness edited is allowed to exist invalid for a length of time. It is ofttimes convenient to enable the user to type invalid values until the commitEdit method is attempted. DefaultFormatter initializes this property to true . Of the standard Swing formatters, only MaskFormatter sets this property to false . |
Examples That Use Formatted Text Fields
This table lists examples that utilize formatted text fields and points to where those examples are described.
Example | Where Described | Notes |
FormattedTextFieldDemo | This section | Uses 4 formatted text fields. |
SpinnerDemo | How to Employ 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. |
TextInputDemo | This section | Shows how to use text fields, spinners, and formatted text fields together, and demonstrates how to use MaskFormatter . Includes code for selecting the text of the field that has just received the focus. |
FormatterFactoryDemo | This department | A variation on FormattedTextFieldDemo that uses formatter factories to specify multiple formatters for 2 formatted text fields. |
Source: https://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html
0 Response to "How to Read Value of a Number From a Jtextfield"
Postar um comentário