When using a JFormattedTextField for floats, I'm unable to see the part after the dot. For instance: if I fill in 3.14, the formatted text field replaces this to 3?

JFormattedTextField aR = new JFormattedTextField(new Float(0.00));

aR.addPropertyChangeListener("value", new PropertyChangeListener() {        
    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        System.out.println(evt.getNewValue());      
    }
}); 
有帮助吗?

解决方案

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.

其他提示

  • you would need to set number of decimal placed in NumberFormat, DecimalNumberFormat

. e.g.

    FormattedTextField.setFormatterFactory(new AbstractFormatterFactory() {

        @Override
        public AbstractFormatter getFormatter(JFormattedTextField tf) {
            NumberFormat format = DecimalFormat.getInstance();
            format.setMinimumFractionDigits(2);
            format.setMaximumFractionDigits(2);
            format.setRoundingMode(RoundingMode.HALF_UP);
            InternationalFormatter formatter = new InternationalFormatter(format);
            formatter.setAllowsInvalid(false);
            formatter.setMinimum(0.0);
            formatter.setMaximum(1000.00);
            return formatter;
        }
    });
  • maybe to use DocumentListener for JTextComponents instead of PropertyChangeListener, depends on if you want to listening for all changes or final result is important only
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top