how to validate the length of 2 or more jtextfield in a single method?

0

I have 2 jtextfield and I want to validate the number of characters they type in them

       text_root_username = new JTextField();
       text_root_username.addKeyListener(this);//////
        text_root_password = new JPasswordField();
        text_root_password.addKeyListener(this);

I accept them with the following method

        @Override
    public void keyTyped(KeyEvent e) {


          if(text_root_password.getText().length()>=8){
        e.consume();
        }
         if(text_root_username.getText().length()>=8) {
        e.consume();
          }
    }

but what happens is that when you get to 8 characters does not let you write some other character in the other jtext and viseversa

    
asked by Luis Rodriguez 16.04.2018 в 04:55
source

1 answer

1

You will have to do the validation doing a capture of the component independently of the other, because if not once you reach that limit of characters in any of them, e will be consumed.

First establish a name for those JTextField

caja1.setName("caja1");
caja2.setName("caja2");

Then in the KeyTyped(KeyEvent e) method we capture the component in this way

Component aux = e.getComponent();

And finally we validate independently each text box by the name the number of characters to enter.

if(aux.getName().equals("caja1")){
    if(caja1.getText().length() >= 8){
          e.consume();
    }
} 
    
answered by 16.04.2018 в 10:50