Java Check If Two JTextField Has The Same Content

2019-09-21 01:26发布

This question already has an answer here:

I have two JTextFields txf1 and txf2.

In both of them I input the same content (for example: "test").

I made and If statement:

if (txf1.getText() == txf2.getText()) {
    System.out.println("Equal");
} else {
    System.out.println("Error");
}

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?

3条回答
姐就是有狂的资本
2楼-- · 2019-09-21 01:45

Use the equals method to compare Strings. == only compares the object reference. equals compares the actual content of the Strings.

Your code should be something like this:

if (txf1.getText().equals(txf2.getText())) {
  System.out.println("Equal");
} else {
  System.out.println("Error");
}
查看更多
孤傲高冷的网名
3楼-- · 2019-09-21 02:01

Also you can use this good practice which makes your text box entries efficient.

if (txf1.getText().trim().equals(txf2.getText().trim())) {
查看更多
We Are One
4楼-- · 2019-09-21 02:02

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())) {

...instead

查看更多
登录 后发表回答