problem when executing event with a certain number of characters

2

I need to execute an event in a textfield called "txtcodigo" when it reaches a length of 8 characters, I did it in such a way that when the length is greater than 7 then it calls the "ticket" function, however it is doing when writing 9 characters in textfield :

private void txtcodigoKeyTyped(java.awt.event.KeyEvent evt) {                                   
        if (txtcodigo.getText().length()>7) {
            ticket();
        }
}      
    
asked by Dexen142 12.06.2017 в 22:08
source

2 answers

2

To execute the method when the length of the text is greater than 7 this is correct, but remember that spaces can add a longer length, use trim () to remove spaces at the ends of the text:

if (txtcodigo.getText().trim().length()>7) { // mayor que 7
    ticket();
}

For example, this String has a length of 8:

String s = "Dexen14 ";
int slength = s.length();

If we apply the method trim () , would have a length of 7, which is the expected value without counting the space:

String s = "Dexen14 ";
int slength = s.trim().length();

Update : the user types "17234752" and wishes that when the last digit is typed, the validation is activated, however this will activate a character later since it is calling the method KeyTyped()

You must use the method keyReleased () so that writing the character and releasing the key was called validation.

@Override
public void keyReleased(KeyEvent e) {
   if (txtcodigo.getText().trim().length()>7) {
        ticket();
    }
}
  

keyReleased ( ) Invoked when a key has been released.

    
answered by 12.06.2017 / 22:25
source
1

I have done an eclipse test and it works for me, when I get to 8 characters. I leave the code:

I have a TextField called textField, and a JLabel called lblNewLabe.

textField.addKeyListener(new KeyListener() {

        @Override
        public void keyTyped(KeyEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void keyReleased(KeyEvent e) {
            // TODO Auto-generated method stub
            if(textField.getText().length()>=8){
                lblNewLabel.setText("8 Caracteres !!");
            }
        }

        @Override
        public void keyPressed(KeyEvent e) {
            // TODO Auto-generated method stub

        }
    });

I've tried it and it works, if you still have problems share a little more code to be able to test your code and find the fault.

    
answered by 12.06.2017 в 22:41