Reputation: 81
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
Upvotes: 1
Views: 773
Reputation: 4713
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.
EDIT:
I'm back at my computer now, and am able to provide a code sample. See below:
userNameTextBox.getDocument().addDocumentListener(new DocumentListener(){
@Override
public void insertUpdate(DocumentEvent e) {
handleTextChange();
}
@Override
public void removeUpdate(DocumentEvent e) {
handleTextChange();
}
@Override
public void changedUpdate(DocumentEvent e) {
//Do nothing here
}
private void handleTextChange(){
if(userNameTextBox.getText() == null ||
userNameTextBox.getText().trim().length() == 0){
passwordBox.setEnabled(false);
}else{
passwordBox.setEnabled(true);
}
}
});
Note that the changedUpdate
method does nothing because it is not fired when the document text changes, it is fired when attributes change. See the javadoc for complete details.
Upvotes: 1