Java检查两个JTextField是否具有相同的内容 [英] Java Check If Two JTextField Has The Same Content
问题描述
我有两个JTextFields txf1和txf2.
I have two JTextFields txf1 and txf2.
我在他们两个人中都输入了相同的内容(例如:"test").
In both of them I input the same content (for example: "test").
我做了if语句:
if (txf1.getText() == txf2.getText()) {
System.out.println("Equal");
} else {
System.out.println("Error");
}
为什么会打印出错误消息?我什至制作了System.out.println(txf1.getText())
和System.out.println(txf2.getText())
,它们看起来相同,但是打印出了错误消息?
Why it prints out the error message? I even made a System.out.println(txf1.getText())
and System.out.println(txf2.getText())
and the same looks equal, but prints out the error message?
推荐答案
Java中的字符串比较是使用String#equals
完成的,使用==
意味着您正在比较对象的内存引用,但并不总是返回true
在您认为应该的时候.
String comparison in Java is done using String#equals
, using ==
means you are comparing the memory reference of the objects, which won't always return true
when you think it should.
尝试更多类似的东西....
Try something more like....
if (txf1.getText().equals(txf2.getText())) {
...相反
这篇关于Java检查两个JTextField是否具有相同的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!