问题
I'm using this code to enable a button when both fields are filled in and disable it when they aren't:
if (jTextFieldAccountName.getText().isEmpty() &&
jPasswordFieldAccountPassword.getPassword().length == 0) {
jButton_Next.setEnabled(false);
} else {
jButton_Next.setEnabled(true);
}
But the button is enabled even if I type in only one of the fields. Why?
回答1:
Your statement is working fine. The way you have it written, the button is going to be disabled only when BOTH fields are empty (if jTextFieldAccountName
is empty AND jPasswordFieldAccountPassword
length equals 0). When you type something into the first field, both fields are no longer empty so the condition sets false, and your button is enabled.
If you want both fields to be input before the button is enabled, change your logic to:
if ((!jTextFieldAccountName.getText().isEmpty()) && (jPasswordFieldAccountPassword.getPassword().length > 0)) {
jButton_Next.setEnabled(true);
}
else {
jButton_Next.setEnabled(false);
}
If you use this logic, you can also set your password to be a minimum length (e.g. password > 6, or something like that).
回答2:
I think you meant to use the OR logical operator i.e. ||
:
If (text-box-is-empty OR password-is-too-small) THEN...
Then try this code:
if ( jTextFieldAccountName.getText().isEmpty()
|| jPasswordFieldAccountPassword.getPassword().length < 6 )
{
jButton_Next.setEnabled(false);
} else {
jButton_Next.setEnabled(true);
}
Note I also changed the password-condition as passwords should be a minimal of 6 characters.
来源:https://stackoverflow.com/questions/18294889/java-on-if-statement-is-not-working