简体   繁体   English

我无法清除JTextArea,如何清除JTextArea?

[英]I cannot clear my JTextArea, how can I clear the JTextArea?

It's a prototype for a virtual therapist, mainly for Java practice purposes. 这是虚拟治疗师的原型,主要用于Java实践。 I've been trying to clear this JTextArea for 2 days now. 我已经尝试清除此JTextArea已有2天了。

I've cleaned and rebuilt which got me through a few other hurdles, I'm at a loss for what to try. 我已经进行了清理和重建,这使我克服了其他一些障碍,但是我对尝试的方法一无所知。 setEnabled() is coded out because I was just trying it on and off with different methods. setEnabled()被编码掉了,因为我只是尝试使用不同的方法来打开和关闭它。 Everything but the clear button works fine. 除了清除按钮以外的所有东西都可以正常工作。 I get a response in the text area after pressing enter with JTextField input. JTextField输入按Enter后,在文本区域中得到响应。 But it just won't clear. 但这还不清楚。

public void actionPerformed(ActionEvent event)
{

   String inp = event.toString(); //this is input in a JTextField

   if(inp.contains("sad") || inp.contains("lonely"))
   {
       txtArea.setText(response1);

   }else if(inp.contains(""))
   {
       txtArea.setText(response2);
   }

   else if(event.getSource() == clear) //clear is a button
   {
     //clear.setEnabled(true); 
     txtArea.setText(""); //I've tried selectAll(), replaceSelection()
   }
}

From what I can see in your code this might help with the clear problem. 从您的代码中可以看到,这可能有助于解决明显的问题。 In your code the if branch for the clear can never be reached due to the else after an condition(contains an emty string) that is always true. 在您的代码中,由于始终为true的条件(包含emty字符串)之后的else,因此永远无法到达clear的if分支。 I moved it to the front - so it is reachable. 我将其移至前端-可以访问。

I can't say for sure from your posted code, but the event.toString() looks also suspicious as well as the last(in the changed code below) condition, that is always true. 我不能从您发布的代码中确定地说,但是event.toString()看起来也很可疑,以及最后一个条件(在下面的更改代码中),这始终是正确的。

   //this looks odd/suspicious to me too!
   String inp = event.toString(); //???!!! this is input in a JTextField
   /* rather something like 
    *  if(event.getSource() instanceof JTextField){
    *      inp = ((JTextField)event.getSource()).getText();
    *  }
    */
   if(event.getSource() == clear) { //clear is a button
     //clear.setEnabled(true); 
     txtArea.setText(""); //I've tried selectAll(), replaceSelection()

   } else if(inp.contains("sad") || inp.contains("lonely")) { 
       txtArea.setText(response1);

   } else if(inp.contains("")) { //??? always true!! rather: inp.equals("") or inp.isEmpty() ...
       txtArea.setText(response2);
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM