无法在追加之前设置 JTextArea 的文本



我在设置 JTextArea 的文本然后附加它时遇到了一些问题。我基本上只想清除文本,然后附加一些其他文本。结果是文本未清除,并且正在追加文本。我提供了一些模拟代码来显示我基本上拥有的内容。

public Constructor(){
textArea = new JTextArea();
textArea.setText("Wow");
someBoolean = false;
someString = "Oh";
}
public someOtherMethod(){
   if(!someBoolean){
     if(textArea.equals("Wow"){
       textArea.setText("");
      } else {
   textArea.append(someString+"n");
   }
 }
}

textArea 是类JTextArea的对象。因此,您的条件textArea.equals("Wow")是不合适的。您正在将 JTextArea 对象与始终返回false的字符串对象进行比较。在JTextArea中比较文本的正确方法如下:

if(textArea.getText().equals("Wow"))

顺便说一下,不要忘记在事件调度线程上调用setText(...)

SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        textArea.setText(...);
    }
});

最新更新