java&&关于if语句不起作用 [英] java && on if statement is not working

查看:104
本文介绍了java&&关于if语句不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码在两个字段都填写时启用一个按钮,而在两个字段都不填写时将其禁用:

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?

推荐答案

您的语句运行正常.编写方式只有在两个字段均为空时(如果jTextFieldAccountName为空且jPasswordFieldAccountPassword长度等于0),该按钮才被禁用.在第一个字段中键入内容时,两个字段都不再为空,因此条件设置为false,并且启用了按钮.

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);
        }

如果使用此逻辑,还可以将密码设置为最小长度(例如,密码> 6,或类似的值).

If you use this logic, you can also set your password to be a minimum length (e.g. password > 6, or something like that).

这篇关于java&&关于if语句不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆