我正在为我制作的游戏编写登录脚本。我目前正在检查所提供的信息以确保其有效。我遇到了一个问题,当我去检查 2 个文本字段是否具有相同的值时。当他们这样做时,他们做的与我想要的相反。
private void regAccConfEmailFieldFocusFocusLost(FocusEvent event) {
if(regAccConfEmailField.getText() == regAccEmail.getText() && regAccConfEmail != null)
{
regAccConfEmailField.setBorder(new LineBorder(Color.green, 1, false));
confEmail = true;
}
else
{
regAccConfEmailField.setBorder(new LineBorder(Color.red, 1, false));
confEmail = false;
}
}
private void regAccConfSecQFieldFocusFocusLost(FocusEvent event) {
if(regAccConfSecQField.getText() == null)
{
regAccConfSecQField.setBorder(new LineBorder(Color.red, 1, false));
secQuestion = false;
}
else
{
regAccConfSecQField.setBorder(new LineBorder(Color.green, 1, false));
secQuestion = true;
}
}
这是我的代码,我需要知道为什么这些方法中的每一个都与给定的相反。
假设 regAccConfEmailField 和 regAccEmailField 都等于 hello@gmail.com 它将转到 if 语句而不是 else。如果需要,我可以提供更多代码。
最佳答案
这个声明有两个问题:
if (regAccConfEmailField.getText() == regAccEmail.getText() && regAccConfEmail != null)
- 您应该首先检查
null
,以便在regAccConfEmail
为null
时短路表达式 - 还使用
String.equals
来比较String
内容,而不是==
运算符。==
运算符用于比较对象引用,目前为您提供与您想要的相反的结果,因为 2 个字段的值将是不同的String
对象。<
可以替换为
if (regAccConfEmail != null && regAccConfEmailField.getText().equals(regAccEmail.getText()))
此外,
regAccConfSecQField.getText()
永远不能是JTextField
中的null
,因此替换if (regAccConfSecQField.getText() == null)
与
if (regAccConfSecQField.getText().trim().isEmpty())
- 最后,您使用的似乎是
FocusListener
,它依赖于FocusEvents
来执行验证。看看使用 DocumentListener用于触发对文档更改的验证。
关于java - 非常奇怪的 Swing 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14077309/