Search code examples
javaswingjformattedtextfield

JFormattedTextField: the formatted text to numbers without spaces


I've got a little problem with JFormattedTextField: I want to hold and retrieve numbers from 1000 to 65535. But when I retriev value (7000) from JFormattedTextField, it have one space like 7 000, and when I parse value to Integer (Integer.parseInt(formattedTextField.getText())), it fail.

java.lang.NumberFormatException: For input string: "7 000"

If I do this with MaskFormatter() and .setMask("#####") it's ok, but I want to do this with NumberFormatter().

How can I setup JFormattedTextField without an additon space?

    NumberFormatter nfsoc   = new NumberFormatter();
    nfsoc.setMaximum(Short.MAX_VALUE*2 - 1);
    nfsoc.setMinimum(1);
    nfsoc.setAllowsInvalid(false);

    formattedTextField      = new JFormattedTextField(nfsoc);

    formattedTextField.setText("7000");      

    int socket              = Integer.parseInt(formattedTextField.getText()) 
    //java.lang.NumberFormatException: For input string: "7 000"

I expect the output of Integer.parseInt(tfServerSocket.getText()) to be 7000, but the actual output is //java.lang.NumberFormatException: For input string: "7 000"


Solution

  • To get rid of addition space:

    NumberFormatter nfsoc   = new NumberFormatter();
    NumberFormat nf         = NumberFormat.getIntegerInstance();
    nf.setGroupingUsed(false); // It removes any separator
    nfsoc.setFormat(nf);
    nfsoc.setMaximum(Short.MAX_VALUE*2 - 1);
    nfsoc.setMinimum(1);
    nfsoc.setAllowsInvalid(false);