开发者

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

开发者 https://www.devze.com 2023-02-07 08:43 出处:网络
I have a requirement in my project. I generate a comment string in javascript. Coping Option: Delete all codes and replace

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 afte开发者_开发问答r 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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消