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?
解决方案
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).