0

Hi I m trying to add a space formating fonctionality to my textfield (I m using JFoenix) my goal is to write 100000 as 10 00 00 and 1000000 as 1 00 00 00

here is my attempt but my result is reverse because the caret is losing position.

public static void setup(JFXTextField textField) {
    textField.setOnKeyReleased(value->{
         String entredText = textField.getText();
         String noSpaced = entredText.replaceAll("\\s+","");
         StringBuilder builder = new StringBuilder();
         for (int i = 0; i < noSpaced.length(); i++) {
             builder.append(noSpaced.charAt(i));
             if (i%2==0) {
                 builder.append(" ");
             }
         }
         textField.setText(builder.toString());
      });
}

for test the issues that I m facing here are : to much spaces and the writing is reversed

thanks to Armel Sahamene answer we have the spacing issue fixed but not the reversing one

123456 should be 12 34 56 but the result is 65 43 21

thanks

2 Answers2

2

Possible solutions are already answered here.

For your case I would recommend to use MaskField.

Dmytro Maslenko
  • 2,247
  • 9
  • 16
1

your format depends on the length of the noSpaced string. so fix your if condition like this:

public static void setup(JFXTextField textField) {
textField.setOnKeyReleased(value->{
     String entredText = textField.getText();
     String noSpaced = entredText.replaceAll("\\s+","");
     StringBuilder builder = new StringBuilder();
     for (int i = 0; i < noSpaced.length(); i++) {
         builder.append(noSpaced.charAt(i));
         if ((i % 2 == 0 && noSpaced.length() % 2 == 1) || (i % 2 == 1 && noSpaced.length() % 2 == 0)) {
             builder.append(" ");
         }
     }
     textField.setText(builder.toString());
  });

}

  • the issue here is there is still the reversed format issue try to write 123987 that should be 12 39 87 but you will get 78 93 21 How to fix this ? knowing is due to the caret position – Mohammed Housseyn Taleb Aug 12 '17 at 23:11