Java Tutorial/Swing/JFormattedTextField — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 15:31, 31 мая 2010
Содержание
- 1 A BigDecimal object custom formatter
- 2 Adding ActionListener to JFormattedTextField
- 3 A decimal number with one digit following the decimal point;
- 4 Characters you can use in the formatting mask
- 5 Creating a Text Field to Display and Edit a Phone Number
- 6 Creating a Text Field to Display and Edit a social security number
- 7 Customizing a JFormattedTextField Look and Feel
- 8 Dynamically change the format
- 9 Formatted Date and Time Input: DateFormat.FULL, Locale.US
- 10 Formatted Date and Time Input: DateFormat.getTimeInstance(DateFormat.SHORT)
- 11 Formatted Date and Time Input: DateFormat.MEDIUM, Locale.ITALIAN
- 12 Formatted Date and Time Input: DateFormat.SHORT
- 13 Formatted Date and Time Input: new SimpleDateFormat(E, Locale.FRENCH)
- 14 Formatted Numeric Input: NumberFormat.getCurrencyInstance(Locale.UK)
- 15 Formatted Numeric Input: NumberFormat.getInstance()
- 16 Formatted Numeric Input: NumberFormat.getIntegerInstance(Locale.ITALIAN)
- 17 Formatted Numeric Input: NumberFormat.getNumberInstance(Locale.FRENCH)
- 18 Formatted Numeric Input: Raw Number
- 19 It implements a mortgage calculator that uses four JFormattedTextFields
- 20 JFormattedTextField
- 21 JFormattedTextField focus lost behaviour
- 22 JFormattedTextField with SimpleDateFormat
- 23 Make custom Input Text Formatter for JFormattedTextField
- 24 Support a date with the custom format: 1
- 25 Using Actions with Text Components: JFormattedTextField
- 26 Using DefaultFormatterFactory to create Date format
A BigDecimal object custom formatter
import java.math.BigDecimal;
import java.text.DecimalFormat;
import javax.swing.JFormattedTextField;
import javax.swing.text.DefaultFormatter;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.NumberFormatter;
public class Main {
public static void main(String[] argv) {
JFormattedTextField f = new JFormattedTextField(new BigDecimal("123.4567"));
DefaultFormatter fmt = new NumberFormatter(new DecimalFormat("#.0###############"));
fmt.setValueClass(f.getValue().getClass());
DefaultFormatterFactory fmtFactory = new DefaultFormatterFactory(fmt, fmt, fmt);
f.setFormatterFactory(fmtFactory);
BigDecimal bigValue = (BigDecimal) f.getValue();
}
}
Adding ActionListener to JFormattedTextField
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.DateFormatter;
import javax.swing.text.DefaultFormatterFactory;
public class FormattedSample {
public static void main(final String args[]) {
JFrame frame = new JFrame("Formatted Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DateFormat displayFormat = new SimpleDateFormat("yyyy--MMMM--dd");
DateFormatter displayFormatter = new DateFormatter(displayFormat);
DateFormat editFormat = new SimpleDateFormat("MM/dd/yy");
DateFormatter editFormatter = new DateFormatter(editFormat);
DefaultFormatterFactory factory = new DefaultFormatterFactory(displayFormatter,
displayFormatter, editFormatter);
JFormattedTextField date2TextField = new JFormattedTextField(factory, new Date());
frame.add(date2TextField, BorderLayout.NORTH);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
JFormattedTextField source = (JFormattedTextField) actionEvent.getSource();
Object value = source.getValue();
System.out.println("Class: " + value.getClass());
System.out.println("Value: " + value);
}
};
date2TextField.addActionListener(actionListener);
frame.add(new JTextField(), BorderLayout.SOUTH);
frame.setSize(250, 100);
frame.setVisible(true);
}
}
A decimal number with one digit following the decimal point;
import java.text.DecimalFormat;
import javax.swing.JFormattedTextField;
public class Main {
public static void main(String[] argv) throws Exception {
JFormattedTextField tft2 = new JFormattedTextField(new DecimalFormat("#.0"));
tft2.setValue(new Float(123.4F));
// Retrieve the value from the text field
Float floatValue = (Float) tft2.getValue();
}
}
Characters you can use in the formatting mask
CharacterDescription#Any valid number (Character.isDigit)."(single quote)Escape character, used to escape any of the special formatting characters.UAny character (Character.isLetter). All lowercase letters are mapped to uppercase.LAny character (Character.isLetter). All uppercase letters are mapped to lowercase.AAny character or number (Character.isLetter or Character.isDigit).?Any character (Character.isLetter).*Anything.HAny hex character (0-9, a-f or A-F).
Creating a Text Field to Display and Edit a Phone Number
import javax.swing.JFormattedTextField;
import javax.swing.text.MaskFormatter;
public class Main {
public static void main(String[] argv) throws Exception {
MaskFormatter fmt = new MaskFormatter("###-###-####");
JFormattedTextField tft1 = new JFormattedTextField(fmt);
}
}
Creating a Text Field to Display and Edit a social security number
import javax.swing.JFormattedTextField;
import javax.swing.text.MaskFormatter;
public class Main {
public static void main(String[] argv) throws Exception{
MaskFormatter fmt = new MaskFormatter("###-###-####");
JFormattedTextField tft1 = new JFormattedTextField(fmt);
fmt = new MaskFormatter("###-##-####");
JFormattedTextField tft2 = new JFormattedTextField(fmt);
}
}
Customizing a JFormattedTextField Look and Feel
Property StringObject TypeFormattedTextField.actionMapActionMapFormattedTextField.backgroundColorFormattedTextField.borderBorderFormattedTextField.caretAspectRatioNumberFormattedTextField.caretBlinkRateIntegerFormattedTextField.caretForegroundColorFormattedTextField.focusInputMapInputMapFormattedTextField.fontFontFormattedTextField.foregroundColorFormattedTextField.inactiveBackgroundColorFormattedTextField.inactiveForegroundColorFormattedTextField.keyBindingsKeyBinding[ ]FormattedTextField.marginInsetsFormattedTextField.selectionBackgroundColorFormattedTextField.selectionForegroundColorFormattedTextFieldUIString
Dynamically change the format
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JFormattedTextField;
import javax.swing.text.DateFormatter;
public class Main {
public static void main(String[] argv) {
JFormattedTextField f = new JFormattedTextField(new SimpleDateFormat("yyyy-M-d"));
f.setValue(new Date());
DateFormatter fmt = (DateFormatter) f.getFormatter();
fmt.setFormat(new SimpleDateFormat("d/M/yyyy"));
f.setValue(f.getValue());
}
}
Formatted Date and Time Input: DateFormat.FULL, Locale.US
import java.awt.FlowLayout;
import java.text.DateFormat;
import java.text.Format;
import java.util.Date;
import java.util.Locale;
import javax.swing.BoxLayout;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class JFormattedTextFieldDateInputSampleDateFormatFULLLocaleUS {
public static void main(String args[]) {
JFrame frame = new JFrame("Date/Time Input");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label;
JFormattedTextField input;
JPanel panel;
BoxLayout layout = new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS);
frame.setLayout(layout);
Format fullUSDate = DateFormat.getDateInstance(DateFormat.FULL, Locale.US);
label = new JLabel("Full US date:");
input = new JFormattedTextField(fullUSDate);
input.setValue(new Date());
input.setColumns(20);
panel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
panel.add(label);
panel.add(input);
frame.add(panel);
frame.add(new JTextField());
frame.pack();
frame.setVisible(true);
}
}
Formatted Date and Time Input: DateFormat.getTimeInstance(DateFormat.SHORT)
import java.awt.FlowLayout;
import java.text.DateFormat;
import java.text.Format;
import java.util.Date;
import javax.swing.BoxLayout;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class JFormattedTextFieldDateFormatgetTimeInstanceDateFormatSHORT {
public static void main(String args[]) {
JFrame frame = new JFrame("Date/Time Input");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label;
JFormattedTextField input;
JPanel panel;
BoxLayout layout = new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS);
frame.setLayout(layout);
Format shortTime = DateFormat.getTimeInstance(DateFormat.SHORT);
label = new JLabel("Short time:");
input = new JFormattedTextField(shortTime);
input.setValue(new Date());
input.setColumns(20);
panel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
panel.add(label);
panel.add(input);
frame.add(panel);
frame.add(new JTextField());
frame.pack();
frame.setVisible(true);
}
}
Formatted Date and Time Input: DateFormat.MEDIUM, Locale.ITALIAN
import java.awt.FlowLayout;
import java.text.DateFormat;
import java.text.Format;
import java.util.Date;
import java.util.Locale;
import javax.swing.BoxLayout;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class JFormattedTextFieldDateInputSampleDateFormatMEDIUMLocaleITALIAN {
public static void main(String args[]) {
JFrame frame = new JFrame("Date/Time Input");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label;
JFormattedTextField input;
JPanel panel;
BoxLayout layout = new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS);
frame.setLayout(layout);
Format mediumItalian = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.ITALIAN);
label = new JLabel("Medium Italian date:");
input = new JFormattedTextField(mediumItalian);
input.setValue(new Date());
input.setColumns(20);
panel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
panel.add(label);
panel.add(input);
frame.add(panel);
frame.add(new JTextField());
frame.pack();
frame.setVisible(true);
}
}
Formatted Date and Time Input: DateFormat.SHORT
import java.awt.FlowLayout;
import java.text.DateFormat;
import java.text.Format;
import java.util.Date;
import javax.swing.BoxLayout;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class JFormattedTextFieldDateInputSampleDateFormatSHORT {
public static void main(String args[]) {
JFrame frame = new JFrame("Date/Time Input");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label;
JFormattedTextField input;
JPanel panel;
BoxLayout layout = new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS);
frame.setLayout(layout);
Format shortDate = DateFormat.getDateInstance(DateFormat.SHORT);
label = new JLabel("Short date:");
input = new JFormattedTextField(shortDate);
input.setValue(new Date());
input.setColumns(20);
panel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
panel.add(label);
panel.add(input);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
Formatted Date and Time Input: new SimpleDateFormat(E, Locale.FRENCH)
import java.awt.FlowLayout;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import javax.swing.BoxLayout;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class JFormattedTextFieldDateInputSampleELocaleFRENCH {
public static void main(String args[]) {
JFrame frame = new JFrame("Date/Time Input");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label;
JFormattedTextField input;
JPanel panel;
BoxLayout layout = new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS);
frame.setLayout(layout);
Format dayOfWeek = new SimpleDateFormat("E", Locale.FRENCH);
label = new JLabel("French day of week:");
input = new JFormattedTextField(dayOfWeek);
input.setValue(new Date());
input.setColumns(20);
panel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
panel.add(label);
panel.add(input);
frame.add(panel);
frame.add(new JTextField());
frame.pack();
frame.setVisible(true);
}
}
Formatted Numeric Input: NumberFormat.getCurrencyInstance(Locale.UK)
import java.awt.FlowLayout;
import java.awt.Font;
import java.text.Format;
import java.text.NumberFormat;
import java.util.Locale;
import javax.swing.BoxLayout;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class NumberInputSampleLocaleUK {
public static void main(String args[]) {
JFrame frame = new JFrame("Number Input");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Font font = new Font("SansSerif", Font.BOLD, 16);
JLabel label;
JFormattedTextField input;
JPanel panel;
BoxLayout layout = new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS);
frame.setLayout(layout);
Format currency = NumberFormat.getCurrencyInstance(Locale.UK);
label = new JLabel("UK Currency:");
input = new JFormattedTextField(currency);
input.setValue(2424.50);
input.setColumns(20);
input.setFont(font);
panel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
panel.add(label);
panel.add(input);
frame.add(panel);
frame.add(new JTextField());
frame.pack();
frame.setVisible(true);
}
}
Formatted Numeric Input: NumberFormat.getInstance()
import java.awt.FlowLayout;
import java.awt.Font;
import java.text.Format;
import java.text.NumberFormat;
import java.util.Locale;
import javax.swing.BoxLayout;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class NumberInputNumberFormatgetInstance {
public static void main(String args[]) {
JFrame frame = new JFrame("Number Input");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Font font = new Font("SansSerif", Font.BOLD, 16);
JLabel label;
JFormattedTextField input;
JPanel panel;
BoxLayout layout = new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS);
frame.setLayout(layout);
Format general = NumberFormat.getInstance();
label = new JLabel("General/Instance:");
input = new JFormattedTextField(general);
input.setValue(2424.50);
input.setColumns(20);
input.setFont(font);
panel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
panel.add(label);
panel.add(input);
frame.add(panel);
frame.add(new JTextField());
frame.pack();
frame.setVisible(true);
}
}
Formatted Numeric Input: NumberFormat.getIntegerInstance(Locale.ITALIAN)
import java.awt.FlowLayout;
import java.awt.Font;
import java.text.Format;
import java.text.NumberFormat;
import java.util.Locale;
import javax.swing.BoxLayout;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class NumberInputNumberFormatgetIntegerInstanceLocaleITALIAN{
public static void main(String args[]) {
JFrame frame = new JFrame("Number Input");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Font font = new Font("SansSerif", Font.BOLD, 16);
JLabel label;
JFormattedTextField input;
JPanel panel;
BoxLayout layout = new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS);
frame.setLayout(layout);
Format integer = NumberFormat.getIntegerInstance(Locale.ITALIAN);
label = new JLabel("Italian integer:");
input = new JFormattedTextField(integer);
input.setValue(2424.50);
input.setColumns(20);
input.setFont(font);
panel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
panel.add(label);
panel.add(input);
frame.add(panel);
frame.add(new JTextField());
frame.pack();
frame.setVisible(true);
}
}
Formatted Numeric Input: NumberFormat.getNumberInstance(Locale.FRENCH)
import java.awt.FlowLayout;
import java.awt.Font;
import java.text.Format;
import java.text.NumberFormat;
import java.util.Locale;
import javax.swing.BoxLayout;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class NumberFormatgetNumberInstanceLocaleFRENCH{
public static void main(String args[]) {
JFrame frame = new JFrame("Number Input");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Font font = new Font("SansSerif", Font.BOLD, 16);
JLabel label;
JFormattedTextField input;
JPanel panel;
BoxLayout layout = new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS);
frame.setLayout(layout);
Format number = NumberFormat.getNumberInstance(Locale.FRENCH);
label = new JLabel("French Number:");
input = new JFormattedTextField(number);
input.setValue(2424.50);
input.setColumns(20);
input.setFont(font);
panel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
panel.add(label);
panel.add(input);
frame.add(panel);
frame.add(new JTextField());
frame.pack();
frame.setVisible(true);
}
}
Formatted Numeric Input: Raw Number
import java.awt.FlowLayout;
import java.awt.Font;
import javax.swing.BoxLayout;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class NumberFormatgetRawNumber{
public static void main(String args[]) {
JFrame frame = new JFrame("Number Input");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Font font = new Font("SansSerif", Font.BOLD, 16);
JLabel label;
JFormattedTextField input;
JPanel panel;
BoxLayout layout = new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS);
frame.setLayout(layout);
label = new JLabel("Raw Number:");
input = new JFormattedTextField(2424.50);
input.setValue(2424.50);
input.setColumns(20);
input.setFont(font);
panel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
panel.add(label);
panel.add(input);
frame.add(panel);
frame.add(new JTextField());
frame.pack();
frame.setVisible(true);
}
}
It implements a mortgage calculator that uses four JFormattedTextFields
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Sun Microsystems nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.NumberFormat;
import javax.swing.BorderFactory;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
/**
* FormattedTextFieldDemo.java requires no other files.
*
* It implements a mortgage calculator that uses four JFormattedTextFields.
*/
public class FormattedTextFieldDemo extends JPanel implements
PropertyChangeListener {
// Values for the fields
private double amount = 100000;
private double rate = 7.5; // 7.5%
private int numPeriods = 30;
// Labels to identify the fields
private JLabel amountLabel;
private JLabel rateLabel;
private JLabel numPeriodsLabel;
private JLabel paymentLabel;
// Strings for the labels
private static String amountString = "Loan Amount: ";
private static String rateString = "APR (%): ";
private static String numPeriodsString = "Years: ";
private static String paymentString = "Monthly Payment: ";
// Fields for data entry
private JFormattedTextField amountField;
private JFormattedTextField rateField;
private JFormattedTextField numPeriodsField;
private JFormattedTextField paymentField;
// Formats to format and parse numbers
private NumberFormat amountFormat;
private NumberFormat percentFormat;
private NumberFormat paymentFormat;
public FormattedTextFieldDemo() {
super(new BorderLayout());
setUpFormats();
double payment = computePayment(amount, rate, numPeriods);
// Create the labels.
amountLabel = new JLabel(amountString);
rateLabel = new JLabel(rateString);
numPeriodsLabel = new JLabel(numPeriodsString);
paymentLabel = new JLabel(paymentString);
// Create the text fields and set them up.
amountField = new JFormattedTextField(amountFormat);
amountField.setValue(new Double(amount));
amountField.setColumns(10);
amountField.addPropertyChangeListener("value", this);
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);
// Tell accessibility tools about label/textfield pairs.
amountLabel.setLabelFor(amountField);
rateLabel.setLabelFor(rateField);
numPeriodsLabel.setLabelFor(numPeriodsField);
paymentLabel.setLabelFor(paymentField);
// Lay out the labels in a panel.
JPanel labelPane = new JPanel(new GridLayout(0, 1));
labelPane.add(amountLabel);
labelPane.add(rateLabel);
labelPane.add(numPeriodsLabel);
labelPane.add(paymentLabel);
// Layout the text fields in a panel.
JPanel fieldPane = new JPanel(new GridLayout(0, 1));
fieldPane.add(amountField);
fieldPane.add(rateField);
fieldPane.add(numPeriodsField);
fieldPane.add(paymentField);
// Put the panels in this panel, labels on left,
// text fields on right.
setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
add(labelPane, BorderLayout.CENTER);
add(fieldPane, BorderLayout.LINE_END);
}
/** 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));
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event dispatch thread.
*/
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("FormattedTextFieldDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add contents to the window.
frame.add(new FormattedTextFieldDemo());
// Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
// Schedule a job for the event dispatch thread:
// creating and showing this application"s GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Turn off metal"s use of bold fonts
UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
}
});
}
// Compute the monthly payment based on the loan amount,
// APR, and length of loan.
double computePayment(double loanAmt, double rate, int numPeriods) {
double I, partial1, denominator, answer;
numPeriods *= 12; // get number of months
if (rate > 0.01) {
I = rate / 100.0 / 12.0; // get monthly rate from annual
partial1 = Math.pow((1 + I), (0.0 - numPeriods));
denominator = (1 - partial1) / I;
} else { // rate ~= 0
denominator = numPeriods;
}
answer = (-1 * loanAmt) / denominator;
return answer;
}
// Create and set up number formats. These objects also
// parse numbers input by user.
private void setUpFormats() {
amountFormat = NumberFormat.getNumberInstance();
percentFormat = NumberFormat.getNumberInstance();
percentFormat.setMinimumFractionDigits(3);
paymentFormat = NumberFormat.getCurrencyInstance();
}
}
JFormattedTextField
The JFormattedTextField provides support for the input of formatted text.
Creating a JFormattedTextField
There are six constructors for the JFormattedTextField class:
public JFormattedTextField()
JFormattedTextField formattedField = new JFormattedTextField();
public JFormattedTextField(Format format)
DateFormat format = new SimpleDateFormat("yyyy--MMMM--dd");
JFormattedTextField formattedField = new JFormattedTextField(format);
public JFormattedTextField(JFormattedTextField.AbstractFormatter formatter)
DateFormat displayFormat = new SimpleDateFormat("yyyy--MMMM--dd");
DateFormatter displayFormatter = new DateFormatter(displayFormat);
JFormattedTextField formattedField = new JFormattedTextField(displayFormatter);
public JFormattedTextField(JFormattedTextField.AbstractFormatterFactory factory)
DateFormat displayFormat = new SimpleDateFormat("yyyy--MMMM--dd");
DateFormatter displayFormatter = new DateFormatter(displayFormat);
DateFormat editFormat = new SimpleDateFormat("MM/dd/yy");
DateFormatter editFormatter = new DateFormatter(editFormat);
DefaultFormatterFactory factory = new DefaultFormatterFactory( displayFormatter, displayFormatter, editFormatter);
JFormattedTextField formattedField = new JFormattedTextField(factory);
public JFormattedTextField(JFormattedTextField.AbstractFormatterFactory factory, Object currentValue)
DateFormat displayFormat = new SimpleDateFormat("yyyy--MMMM--dd");
DateFormatter displayFormatter = new DateFormatter(displayFormat);
DateFormat editFormat = new SimpleDateFormat("MM/dd/yy");
DateFormatter editFormatter = new DateFormatter(editFormat);
DefaultFormatterFactory factory = new DefaultFormatterFactory(displayFormatter, displayFormatter, editFormatter);
JFormattedTextField formattedField = new JFormattedTextField(factory, new Date());
public JFormattedTextField(Object value)
JFormattedTextField formattedField = new JFormattedTextField(new Date());
JFormattedTextField focus lost behaviour
- For a JFormattedTextField, the validation is controlled by the focusLostBehavior property.
- This can be set to one of four values:
- COMMIT_OR_REVERT: This is the default. When the component loses focus, the component automatically calls the commitEdit() method. This will parse the component"s contents and throw a ParseException on error, reverting the contents to the most recent valid value.
- COMMIT: This setting is similar to COMMIT_OR_REVERT, but it leaves the invalid contents within the field, allowing the user to modify the setting.
- REVERT: This setting always reverts the value.
- PERSIST: This setting does nothing. You should manually call commitEdit() yourself to see if the contents are valid before using the contents.
JFormattedTextField with SimpleDateFormat
import java.awt.BorderLayout;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class FormattedSample {
public static void main(final String args[]) {
JFrame frame = new JFrame("Formatted Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel datePanel = new JPanel(new BorderLayout());
DateFormat format = new SimpleDateFormat("yyyy--MMMM--dd");
JFormattedTextField dateTextField = new JFormattedTextField(format);
datePanel.add(dateTextField, BorderLayout.CENTER);
frame.add(datePanel, BorderLayout.NORTH);
frame.add(new JTextField(), BorderLayout.SOUTH);
frame.setSize(250, 100);
frame.setVisible(true);
}
}
Make custom Input Text Formatter for JFormattedTextField
import java.text.ParseException;
import javax.swing.JFormattedTextField;
import javax.swing.text.DefaultFormatter;
class MyFormatter extends DefaultFormatter {
public MyFormatter() {
super();
}
public String valueToString(Object object) throws ParseException {
return super.valueToString(object);
}
public Object stringToValue(String string) throws ParseException {
try {
int value = Integer.parseInt(string);
if (value != 1) {
return "" + value;
} else {
return "Invalid";
}
} catch (Exception e) {
return "Invalid";
}
}
}
public class Main {
public static void main(String[] args) {
JFormattedTextField tf = new JFormattedTextField(new MyFormatter());
tf.setColumns(10);
}
}
Support a date with the custom format: 1
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JFormattedTextField;
public class Main {
public static void main(String[] argv) throws Exception {
JFormattedTextField tft3 = new JFormattedTextField(new SimpleDateFormat("yyyy-M-d"));
tft3.setValue(new Date());
Date date = (Date) tft3.getValue();
}
}
Using Actions with Text Components: JFormattedTextField
import java.util.Arrays;
import java.util.ruparator;
import javax.swing.Action;
import javax.swing.JFormattedTextField;
import javax.swing.text.JTextComponent;
public class ListActionsJFormattedTextField {
public static void main(String args[]) {
JTextComponent component = new JFormattedTextField();
// Process action list
Action actions[] = component.getActions();
// Define comparator to sort actions
Comparator<Action> comparator = new Comparator<Action>() {
public int compare(Action a1, Action a2) {
String firstName = (String) a1.getValue(Action.NAME);
String secondName = (String) a2.getValue(Action.NAME);
return firstName.rupareTo(secondName);
}
};
Arrays.sort(actions, comparator);
int count = actions.length;
System.out.println("Count: " + count);
for (int i = 0; i < count; i++) {
System.out.printf("%28s : %s\n",actions[i].getValue(Action.NAME),actions[i].getClass().getName());
}
}
}
Count: 55 beep : javax.swing.text.DefaultEditorKit$BeepAction caret-backward : javax.swing.text.DefaultEditorKit$NextVisualPositionAction caret-begin : javax.swing.text.DefaultEditorKit$BeginAction caret-begin-line : javax.swing.text.DefaultEditorKit$BeginLineAction caret-begin-paragraph : javax.swing.text.DefaultEditorKit$BeginParagraphAction caret-begin-word : javax.swing.text.DefaultEditorKit$BeginWordAction caret-down : javax.swing.text.DefaultEditorKit$NextVisualPositionAction caret-end : javax.swing.text.DefaultEditorKit$EndAction caret-end-line : javax.swing.text.DefaultEditorKit$EndLineAction caret-end-paragraph : javax.swing.text.DefaultEditorKit$EndParagraphAction caret-end-word : javax.swing.text.DefaultEditorKit$EndWordAction caret-forward : javax.swing.text.DefaultEditorKit$NextVisualPositionAction caret-next-word : javax.swing.text.DefaultEditorKit$NextWordAction caret-previous-word : javax.swing.text.DefaultEditorKit$PreviousWordAction caret-up : javax.swing.text.DefaultEditorKit$NextVisualPositionAction copy-to-clipboard : javax.swing.text.DefaultEditorKit$CopyAction cut-to-clipboard : javax.swing.text.DefaultEditorKit$CutAction default-typed : javax.swing.text.DefaultEditorKit$DefaultKeyTypedAction delete-next : javax.swing.text.DefaultEditorKit$DeleteNextCharAction delete-previous : javax.swing.text.DefaultEditorKit$DeletePrevCharAction dump-model : javax.swing.text.DefaultEditorKit$DumpModelAction insert-break : javax.swing.text.DefaultEditorKit$InsertBreakAction insert-content : javax.swing.text.DefaultEditorKit$InsertContentAction insert-tab : javax.swing.text.DefaultEditorKit$InsertTabAction notify-field-accept : javax.swing.JFormattedTextField$CommitAction page-down : javax.swing.text.DefaultEditorKit$VerticalPageAction page-up : javax.swing.text.DefaultEditorKit$VerticalPageAction paste-from-clipboard : javax.swing.text.DefaultEditorKit$PasteAction reset-field-edit : javax.swing.JFormattedTextField$CancelAction select-all : javax.swing.text.DefaultEditorKit$SelectAllAction select-line : javax.swing.text.DefaultEditorKit$SelectLineAction select-paragraph : javax.swing.text.DefaultEditorKit$SelectParagraphAction select-word : javax.swing.text.DefaultEditorKit$SelectWordAction selection-backward : javax.swing.text.DefaultEditorKit$NextVisualPositionAction selection-begin : javax.swing.text.DefaultEditorKit$BeginAction selection-begin-line : javax.swing.text.DefaultEditorKit$BeginLineAction selection-begin-paragraph : javax.swing.text.DefaultEditorKit$BeginParagraphAction selection-begin-word : javax.swing.text.DefaultEditorKit$BeginWordAction selection-down : javax.swing.text.DefaultEditorKit$NextVisualPositionAction selection-end : javax.swing.text.DefaultEditorKit$EndAction selection-end-line : javax.swing.text.DefaultEditorKit$EndLineAction selection-end-paragraph : javax.swing.text.DefaultEditorKit$EndParagraphAction selection-end-word : javax.swing.text.DefaultEditorKit$EndWordAction selection-forward : javax.swing.text.DefaultEditorKit$NextVisualPositionAction selection-next-word : javax.swing.text.DefaultEditorKit$NextWordAction selection-page-down : javax.swing.text.DefaultEditorKit$VerticalPageAction selection-page-left : javax.swing.text.DefaultEditorKit$PageAction selection-page-right : javax.swing.text.DefaultEditorKit$PageAction selection-page-up : javax.swing.text.DefaultEditorKit$VerticalPageAction selection-previous-word : javax.swing.text.DefaultEditorKit$PreviousWordAction selection-up : javax.swing.text.DefaultEditorKit$NextVisualPositionAction set-read-only : javax.swing.text.DefaultEditorKit$ReadOnlyAction set-writable : javax.swing.text.DefaultEditorKit$WritableAction toggle-componentOrientation : javax.swing.text.DefaultEditorKit$ToggleComponentOrientationAction unselect : javax.swing.text.DefaultEditorKit$UnselectAction
Using DefaultFormatterFactory to create Date format
import java.awt.BorderLayout;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.DateFormatter;
import javax.swing.text.DefaultFormatterFactory;
public class FormattedSample {
public static void main(final String args[]) {
JFrame frame = new JFrame("Formatted Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DateFormat displayFormat = new SimpleDateFormat("yyyy--MMMM--dd");
DateFormatter displayFormatter = new DateFormatter(displayFormat);
DateFormat editFormat = new SimpleDateFormat("MM/dd/yy");
DateFormatter editFormatter = new DateFormatter(editFormat);
DefaultFormatterFactory factory = new DefaultFormatterFactory(displayFormatter,
displayFormatter, editFormatter);
JFormattedTextField date2TextField = new JFormattedTextField(factory, new Date());
frame.add(date2TextField, BorderLayout.NORTH);
frame.add(new JTextField(), BorderLayout.SOUTH);
frame.setSize(250, 100);
frame.setVisible(true);
}
}