For instance: if I fill in 3.14, the formatted text field replaces this to 3?
Not likely 3
, but 3.1
.
Because when you call the constructor new JFormattedTextField(Object)
,it calls setValue(object)
function which will eventually try to create a formatter factory
corresponding to the Type of object value
by calling getDefaultFormatterFactory(Object type)
function, in which the default formatter
for float
is created as follows:
if (type instanceof Number) {
AbstractFormatter displayFormatter = new NumberFormatter();
((NumberFormatter)displayFormatter).setValueClass(type.getClass());
AbstractFormatter editFormatter = new NumberFormatter(
new DecimalFormat("#.#"));
((NumberFormatter)editFormatter).setValueClass(type.getClass());
return new DefaultFormatterFactory(displayFormatter,
displayFormatter,editFormatter);
}
From this code, you should have noticed that it creates the DecimalFormat
with mask "#.#"
.
So try adding the DecimalFormat
with mask "#.##"
in the JFormattedTextField
constructor:
JFormattedTextField feild = new JFormattedTextField(new DecimalFormat("#.##"));
feild.setValue(new Float(3.34));
and you should be good to go.