I'm having some trouble setting text of a JTextArea and then appending it. I basically just want to clear the text and then append some other text after that. The result is that the text is not clearing and the text is being appended. I've provided some mock up code to show what I basically have.

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 is an object of the class JTextArea. Therefore, your condition textArea.equals("Wow") is inappropriate. You are comparing JTextArea object to String object what always returns false. Proper way how to compare text inside JTextArea is following:

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

By the way, do not forget to call setText(...) on event dispatch thread:

SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        textArea.setText(...);
    }
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top