关于java:从JTextArea清除文本

Clear text from a JTextArea

我在jPanel上写文本:当我按下一个按钮时,它显示有关该按钮的文本,当我按下另一个按钮时,显示有关该按钮的文本,依此类推...

文本区域是这样创建的:

1
2
3
4
5
6
    JTextArea log = new JTextArea(1,20);
    log.setMargin(new Insets(5,5,5,5));
    log.setEditable(false);
    JScrollPane logScrollPane = new JScrollPane(log);

    add(logScrollPane, BorderLayout.CENTER);

当我显示一些文本时:

1
log.append("No file path specified");

我无法删除之前的文字。 例如,如果我按两次相同的按钮,我得到的字符串

"No file path specifiedNo file path specified"

我无法清除文本区域以仅显示新字符串。 我尝试过:

1
log.removeAll();

在log.append()之前,但是没有用。


使用log.setText(null)log.setText(""),相同

您应该尝试使用log.setText("No file path specified");,而不是附加文本,它将用新的String替换当前内容(谢谢Dave)

您可能需要花一些时间通读使用文本组件以了解更多详细信息


尝试从JTextComponent超类获取setText

setText("")

http://docs.oracle.com/javase/6/docs/api/javax/swing/text/JTextComponent.html#setText%28java.lang.String%29