Need to get a multiline string to display in a textbox Java

不羁岁月 提交于 2019-12-06 09:29:11

In java I am trying to replace the \n to

Don't replace the "\n". A JTextArea will parse that as a new line string.

Trying to convert it to a "br" tag won't help either since a JTextArea does not support html.

I always just use code like the following to populate a text area with text:

JTextArea textArea = new JTextArea(5, 20);
textArea.setText("1\n2\n3\n4\n5\n6\n7\n8\n9\n0");
// automatically wrap lines
jTextArea.setLineWrap( true );
// break lines on word, rather than character boundaries.
jTextArea.setWrapStyleWord( true );

From here.

shiva

Here is a test that works, try it out:

String str = "This is a test\r\n test.";
if(str.contains("\r\n")) {
    System.out.println(str);
}

Assuming Javascript (since you try to replace with a HTML break line):

A HTML textarea newline should be a newline character \n and not the HTML break line <br>. Try to use the code below to remove extra slashes instead of your current if statement and replace. Don't forget to assign the value to the textarea after the replacement.

Try:

str = str.replaceAll("\\n", "\n");

I think your problem is here:

if(str.contains("\\n")){

Instead of "\\n" you just need "\n"

Then instead of "\n" you need "\\n" here:

str = str.replaceAll("(\r\n|\n)", "<br>");

By the way, the if(str.contains() is not really needed because it won't hurt to run replace all if there is no "\n" characters.

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