2012-12-29 84 views
1

我正在为我制作的游戏写一个登录脚本。我目前正在检查提供的信息以确保其有效。我遇到了这个问题,当我去检查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都等于[email protected] 它会去if语句,而不是其他。如果需要,我可以提供更多的代码。

回答

4

有2个问题,有这样的说法:

if (regAccConfEmailField.getText() == regAccEmail.getText() && regAccConfEmail != null) 
  • 你应该有null首先检查,使其短路,如果regAccConfEmailnull
  • 还可以使用String.equals比较String内容表达而不是==运营商。 ==运算符用于比较对象引用,并且当前给出的结果与所需值相反,因为来自2个字段的值将不同于String对象。

您可以

if (regAccConfEmail != null && regAccConfEmailField.getText().equals(regAccEmail.getText())) 
  • 而且regAccConfSecQField.getText()取代永远不能从JTextFieldnull所以更换

    如果(regAccConfSecQField.getText()== NULL)

if (regAccConfSecQField.getText().trim().isEmpty()) 
  • 最后,你似乎是使用FocusListener这relys上FocusEvents进行验证。查看使用DocumentListener触发文档更改的验证。
+0

好吧,我对这个还是有点新的。我目前是我高中的二年级学生。非常感谢! – Synposis

+0

不客气! :) – Reimeus

+0

尽管这有帮助,但它并没有解决我的问题D = – Synposis