首页 > 解决方案 > how can i force Jformattedtextfield to add commas before every 3 digits in java

问题描述

I have a problem with JFormattedTextField I want a JFormattedTextField so when user type a number, it separate number with a comma
example : user type: 1234 JFormattedTextField show 1,234
or user type: 123456 JFormattedTextField show 123,456 or user type: 1234567 JFormattedTextField show 1,234,567

I try following code in KeyTypped Event
formattedTextField = new JFormattedTextField();

    formattedTextField.setBounds(56, 159, 152, 29);


    panel_1.add(formattedTextField);

        formattedTextField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {

                  for (int i = len - 1; i >= 0; i--)                      
                  {
                      result = s.charAt(i) + result;                 
                      nDigits++;                                          
                      if (((nDigits % 3) == 0) && (i > 0))                
                      {
                          result = "," + result;
                      }
                  }

                  formattedTextField.setText(result);

});

everything is fine but two problem still exist 1- for example, i press 5 jformattedtextfield show me 55 i press 4 it show 44 2- when i press backspace, jformattedtextfield doesn`t delete a number and instead of this, type a small square for example : i press 1 formattedtextfield show me 11 i press backspace formattedtextfield show me 11 with a blank square

please help me .

thank you all in advance

标签: javajformattedtextfield

解决方案


推荐阅读