Java Reference
In-Depth Information
panel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
panel.add(label);
panel.add(input);
frame.add(panel);
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);
label = new JLabel("Raw Number:");
input = new JFormattedTextField(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.pack();
frame.setVisible(true);
}
};
EventQueue.invokeLater(runner);
}
}
The last of the five
JFormattedTextField
examples in Figure 16-7 initializes the component
with a
double
. The value 2424.50 is auto-boxed into a
Double
object. There's nothing wrong
with passing an object to the constructor. However, you might notice some irregularities while
entering values into the field. A value seems to always start with one decimal point, even though
more input digits are accepted. Instead of using a
Format
object to go from text to
Object
and
back, the
Double
constructor that accepts a
String
is used.
When you pass in a
java.text.Format
object to the
JFormattedTextField
constructor, this
internally is mapped to either a
DateFormatter
or
NumberFormatter
object. Both of these are
subclasses of the
InternationalFormatter
class. The inner class named
JFormattedTextField.
AbstractFormatterFactory
manages the use of the formatter objects within
JFormattedTextField
.
The factory will
install()
the formatter as the user enters the
JFormattedTextField
and
uninstall()
it on departure, ensuring the formatter is active in only one text field at a time.
These
install()
and
uninstall()
methods are inherited by the formatter classes from the
JFormattedTextField.AbstractFormatter
superclass of all formatters.