-1

I want to add - mark after 3 number to a jtextfield for phone number. But here I'm loosing typed numbers. EX 099-1234534

jTextField3.addKeyListener(new KeyAdapter() {
    public void keyTyped(KeyEvent e) {
        char c = e.getKeyChar();
             int MAX_LEN = 9;
                int len = jTextField3.getText().length();
            if ((c >= '0') && (c <= '9') ) {
               if(len == 3){

               jTextField3.setText("-");
            }
                if(len < MAX_LEN){
                jLabel24.setText("");
                return;
            }
            else if (len > MAX_LEN) {
                jLabel24.setText("Cannot Enter More than Four Numbers");
                e.consume();

            }     
            }
            else
            {
             e.consume();
             jLabel24.setText("Invalid Text");
            }
    }
  });
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
  • try replacing `jTextField3.setText("-");` with `jTextField3.setText(jTextField3.getText() + "-");` – Coderino Javarino Jul 17 '16 at 11:09
  • change your jtextfield with a jformattedtextfield, which add support for formatted data. Have a look to MaskFormatter too: http://docs.oracle.com/javase/7/docs/api/javax/swing/text/MaskFormatter.html – spi Oct 10 '17 at 11:33

1 Answers1

0

jTextField3.setText("-") delets everything you've typed into the Textfield so far. So you first need to read the existing text in the textfield, concatenate it with "-" and set it back via setText.

Jannek S.
  • 365
  • 3
  • 16