简体   繁体   中英

NumberFormatter not behaving as expected

I didn't find any java question that helped me solve my problem, so here I come.

I'm currently trying to use a NumberFormatter with a JFormattedTextField to format a price in a GUI as the user types it in.

But I'm getting strange results after typing 2 digits in the textfield.

Here the code I use to test (Netbeans 8.0 + JDK 1.7.0_51):

    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    JFrame frame = new JFrame("");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
    symbols.setDecimalSeparator('.');
    symbols.setGroupingSeparator(' ');
    symbols.setCurrencySymbol("EUR");

    DecimalFormat format = new DecimalFormat("¤ #,##0.00", symbols);
    format.setMaximumFractionDigits(2);
    format.setGroupingUsed(true);

    NumberFormatter formatter = new NumberFormatter(format);
    formatter.setMinimum(    0.00);
    formatter.setMaximum(9_999.99);
    formatter.setAllowsInvalid(false);
    formatter.setOverwriteMode(true);

    JFormattedTextField field = new JFormattedTextField(formatter);
    field.setColumns(10);
    field.setValue(0.33);

    frame.add(field);
    frame.pack();
    frame.setVisible(true);
    frame.setLocationRelativeTo(null);

What I expect :

    // Step             Text in TextField
    // 1: GUI started   EUR <caret>0.33
    // 2: '1' pressed   EUR 1<caret>.33
    // 3: '2' pressed   EUR 12<caret>.33

What I get :

    // Step             Text in TextField
    // 1: start GUI   EUR <caret>0.33     [OK]
    // 2: press '1'   EUR 1<caret>.33     [OK]
    // 3: press '2'   EUR 1 2<caret>33.00 [NOK, see expected result above]

To me it looks like the Formatter does (for step 3) :

  • insert '2' at the caret position -> EUR 12.33
  • remove all 'formatting characters' -> 1233
  • Formats the result of the "removal" again -> EUR 1 233.00

Is this the default behavior for the NumberFormatter? If yes, am I missing something in the setup of the formatter or do I need to write a custom one? If not, what am I doing wrong?

Regards,

Xan.

.

import java.awt.*;
import java.math.*;
import java.text.*;
import javax.swing.*;
import javax.swing.JFormattedTextField.AbstractFormatter;
import javax.swing.JFormattedTextField.AbstractFormatterFactory;
import javax.swing.text.InternationalFormatter;

public class DocumentListenerAdapter {

    public DocumentListenerAdapter() {
        JFrame frame = new JFrame("AbstractTextField Test");
        final JFormattedTextField textField1 = new JFormattedTextField(new Float(10.01));
        textField1.setFormatterFactory(new AbstractFormatterFactory() {
            @Override
            public AbstractFormatter getFormatter(JFormattedTextField tf) {

                DecimalFormatSymbols symbols = new DecimalFormatSymbols();
                symbols.setDecimalSeparator('.');
                symbols.setGroupingSeparator(' ');
                symbols.setCurrencySymbol("EUR");

                DecimalFormat format = new DecimalFormat("¤ #,##0.00", symbols);
                format.setMaximumFractionDigits(2);
                format.setGroupingUsed(true);

                //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(9000.00);
                return formatter;
            }
        });
        NumberFormat numberFormat = NumberFormat.getNumberInstance();
        numberFormat.setMaximumFractionDigits(2);
        numberFormat.setMaximumFractionDigits(2);
        numberFormat.setRoundingMode(RoundingMode.HALF_UP);
        final JFormattedTextField textField2 = new JFormattedTextField(numberFormat);
        textField2.setValue(new Float(10.01));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(textField1, BorderLayout.NORTH);
        frame.add(textField2, BorderLayout.SOUTH);
        frame.setVisible(true);
        frame.pack();
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new DocumentListenerAdapter();
            }
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM