Java 在 JtextArea 的末尾添加一个新行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2088016/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:25:13  来源:igfitidea点击:

Add a new line to the end of a JtextArea

javaswingjtextarea

提问by Johanna

I have a text area with some text in it and I want to add some lines to it again, (the first lines + the other lines that I want to add) but it doesn't work.

我有一个文本区域,其中有一些文本,我想再次向其中添加一些行(第一行 + 我想添加的其他行),但它不起作用。

The way I'm doing it right now erases the old text and shows just the new lines.

我现在这样做的方式是擦除旧文本并仅显示新行。

采纳答案by jjnguy

Instead of using JTextArea.setText(String text), use JTextArea.append(String text).

而不是使用JTextArea.setText(String text),使用JTextArea.append(String text)

Appends the given text to the end of the document. Does nothing if the model is null or the string is null or empty.

将给定的文本附加到文档的末尾。如果模型为空或字符串为空或空,则不执行任何操作。

This will add text on to the end of your JTextArea.

这会将文本添加到您的JTextArea.

Another option would be to use getText()to get the text from the JTextArea, then manipulate the String (add or remove or change the String), then use setText(String text)to set the text of the JTextAreato be the new String.

另一种选择是使用getText()从 获取文本JTextArea,然后操作字符串(添加或删除或更改字符串),然后使用setText(String text)将 的文本设置JTextArea为新字符串。

回答by Adamski

Are you using JTextArea's append(String)method to add additional text?

您是否使用JTextAreaappend(String)方法添加附加文本?

JTextArea txtArea = new JTextArea("Hello, World\n", 20, 20);
txtArea.append("Goodbye Cruel World\n");

回答by user2089755

When you want to create a new line or wrap in your TextArea you have to add \n (newline) after the text.

当您想在 TextArea 中创建新行或换行时,您必须在文本后添加 \n(换行符)。

TextArea t = new TextArea();
t.setText("insert text when you want a new line add \nThen more text....);
setBounds();
setFont();
add(t);

This is the only way I was able to do it, maybe there is a simpler way but I havent discovered that yet.

这是我能够做到的唯一方法,也许有更简单的方法,但我还没有发现。