Nolan Kr Nolan Kr - 13 days ago 5
Java Question

How to disable jTextfield again when the other jTextfield is empty in java

Heya guys! Nolankr here.


I've got this code that

enables
my
password jField
when I place something inside the
username jField
but when I delete my inputs from the
username jField
my
password jField
stays enabled. I wanted it to go back to being disabled though. I'm still a starter so I'm so sorry.

private void usernameKeyTyped(java.awt.event.KeyEvent evt) {
String usern = username.getText();

if(usern != null){
password.setEnabled(true);
}else{
password.setEnabled(false);

}
}


I tried coding an infinite loop to it but it just made my .jar file to stop responding / won't close, so I had to close netbeans itself and restart it . xD


username
and
password
are both jTextfields by the way and
password
is disabled by default


basically,

if username != null then enable password but if username = null again then disable password again

Answer

What you probably want is a document listener that will allow you to detect when the username field is changed and take appropriate action.

I'm writing this answer with the mobile app so it's hard to provide a code sample right now.

Basically you would set up the listener on username to check if username is null or empty and enable/disable the password field based on the result of that check.