java && on if statement is not working

点点圈 提交于 2019-12-13 02:19:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!