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

倖福魔咒の 提交于 2019-12-08 02:01:44

问题


I have a requirement in my project. I generate a comment string in javascript.

Coping Option: Delete all codes and replace
Source Proj Num: R21AR058864-02
Source PI Last Name: SZALAI
Appl ID: 7924675; File Year: 7924675

I send this to server where I store it as a string in db and then after that I retrieve it back and show it in a textarea.

I generate it in javascript as :

        codingHistoryComment += 'Source Proj Num: <%=mDefault.getFullProjectNumber()%>'+'\n';
  codingHistoryComment += 'Source PI Last Name: <%=mDefault.getPILastName()%>'+'\n';
  codingHistoryComment += 'Appl ID: <%=mDefault.getApplId()%>; File Year: <%=mDefault.getApplId()%>'+'\n';

In java I am trying to replace the \n to
:

    String str = soChild2.getChild("codingHistoryComment").getValue().trim();
 if(str.contains("\\n")){
  str = str.replaceAll("(\r\n|\n)", "<br>");
 }

However the textarea still get populated with the "\n" characters:

Coping Option: Delete all codes and replace\nSource Proj Num: R21AR058864-02\nSource PI Last Name: SZALAI\nAppl ID: 7924675; File Year: 7924675\n

Thanks.


回答1:


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");



回答2:


// automatically wrap lines
jTextArea.setLineWrap( true );
// break lines on word, rather than character boundaries.
jTextArea.setWrapStyleWord( true );

From here.




回答3:


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);
}



回答4:


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");



回答5:


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.



来源:https://stackoverflow.com/questions/4846424/need-to-get-a-multiline-string-to-display-in-a-textbox-java

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