Search code examples
javajtextfield

java enable the second textfield if the first textfield is not empty


I have 2 textfields in my project. The first textfield is txtNumA and the second is txtNumB. I disabled txtNumB. When txtNumA is not empty, txtNumB will be enabled.

Well, this is part of code I've tried:

private void txtNumKeyTyped(java.awt.event.KeyEvent evt) {                                   
    if(!(txtNumA.getText().trim().equals(""))){  
        txtNumB.setEnabled(true); 
    }
    else { 
        txtNumB.setText(null);
        txtNumB.setEnabled(false);
    } 
}

Actually it works, but not perfect. It works only if I typed 2 or more characters in txtNumA. What I need is when I typed one character and more, txtNumB will be enabled.

What's wrong with my code?


Solution

  • What is happening here is,

    In case of KeyTyped and KeyPressed events the input is not still given to the TextField.That's why it is not working and works after you type the second character and by that time first character must have reached the TextField.So use KeyReleased method to handle this case.

    t is the first TextField and t1 is second.

    t.addKeyListener(new KeyListener(){
    
            @Override
            public void keyTyped(KeyEvent e) {
    
            }
    
            @Override
            public void keyPressed(KeyEvent e) {
    
            }
    
            @Override
            public void keyReleased(KeyEvent e) {
                JTextField bt = (JTextField)e.getSource();
                if(bt.getText().trim().length()>0){
                    t1.setEnabled(true);
                }
                else
                    t1.setEnabled(false);
            }
        });