textarea.getText() 在 Java 中无法正常工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6593359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 08:03:07  来源:igfitidea点击:

textarea.getText() is not working properly in Java

javastringswingactionlistenerjtextarea

提问by Wassim AZIRAR

I have a JTextArea, and I'm trying to do a stupid test using textarea.getText()

我有一个 JTextArea,我正在尝试使用 textarea.getText() 做一个愚蠢的测试

if(textarea.getText() == "")
{
    System.out.println("empty string");
}

When I do this I don't get anything on the screen even if I leave the textarea empty or I type something inside of it.

当我这样做时,即使我将 textarea 留空或在其中输入一些内容,我也不会在屏幕上看到任何内容。

if(textarea.getText() != "")
{
    System.out.println("empty string");
}

But when I do this one I get the "empty string" message in all cases.

但是当我这样做时,我在所有情况下都会收到“空字符串”消息。

What's the problem here ?

这里有什么问题?

采纳答案by wjans

When comparing strings you should use equalsinstead of ==:

比较字符串时,您应该使用equals而不是==

if("".equals(textarea.getText()))
{
   System.out.println("empty string");
}

==will compare references, it will only work in case it's the exact same String instance. If you want to check whether the content of the String is the same, you should use equals method.

==将比较引用,它仅在它是完全相同的 String 实例的情况下才有效。如果要检查 String 的内容是否相同,则应使用 equals 方法。

回答by 01es

Please use "".equals(textarea.getText()) instead of reference comparison. Operator == compares object references.

请使用 "".equals(textarea.getText()) 而不是引用比较。运算符 == 比较对象引用。

回答by Mark Pope

Your code should use .equals() :

你的代码应该使用 .equals() :

if(textarea.getText().equals(""))
{
    System.out.println("empty string");
}

== compares the object reference rather than the object value

== 比较对象引用而不是对象值

回答by Radium

Alternatively, you can use isEmpty method in this case:

或者,您可以在这种情况下使用 isEmpty 方法:

if(textarea.getText().isEmpty())
{
    System.out.println("empty string");
}