How to add text to a textArea instead of replacing it

巧了我就是萌 提交于 2021-02-17 21:37:17

问题


How can I add text to a JTextArea instead of replacing all of it?

I know about setText(String) but other than that I'm a bit lost.


回答1:


You can use the append method like this:

textArea.append(additionalText);



回答2:


To insert string at any position you can use the component's Document.

public static void main(String[] args) throws BadLocationException {
    JTextField f = new JTextField("foo bar");
    int offset = 7;
    String str = " baz";
    f.getDocument().insertString(offset, str, SimpleAttributeSet.EMPTY);
    System.out.println(f.getText());
}



回答3:


void append(JTextArea area, String newText){
        area.setText(area.getText() + newText)
}


来源:https://stackoverflow.com/questions/12216494/how-to-add-text-to-a-textarea-instead-of-replacing-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!