Reputation: 1
I've tried to add some HTML/CSS in the text of a JEditorPane. Also setText()
method is overridden in this class.
When I insert more than 14 lines in the pane then run makeLineHighlight()
or run makeLineHighlight()
twice on the text of pane, some of the lines get deleted or I got some exceptions. When text of the pane change (I check it in a loop) then I use overridden setText()
to make a numeric list in the pane.
As I delete super.setText()
the code works properly.
@Override
public void setText(String text) {
String bufferText = "<ol style=\"margin-left: 20px;" +
"font-family: Courier New, Courier, monospace;\" >";
String[] linesBuffer = text.split(System.lineSeparator());
for (int i = 0; i < linesBuffer.length; i++) {
bufferText += "<li style=\"\">" + linesBuffer[i] + "</li>" + System.lineSeparator();
}
bufferText += "</ol>";
int pos=this.getCaretPosition();
super.setText(bufferText);
if(pos>getDocument().getLength())pos=getDocument().getLength();
try {
setCaretPosition(pos + 1);
}catch (IllegalArgumentException e){
setCaretPosition(pos);
}
lastText = this.getText();
}
public void makeLineHighlight(int lineNumber){
String bufferText="";
String[] linesOfText=super.getText().split(System.lineSeparator());
for (int i = 0; i < linesOfText.length; i++) {
if(i==(6+((lineNumber-1)*3))){
bufferText+="<li style=\"background-color: #EA2A40\">\n "+linesOfText[i+1]+"\n</li>\n";
i+=2;
continue;
}
bufferText+=linesOfText[i]+System.lineSeparator();
}
super.setText(bufferText);
}
Upvotes: 0
Views: 78
Reputation: 356
Your input text is HTML/CSS
. Note that The line break in HTML is <br />
, not System.lineSeparator()
and you use \n
in your new HTML code, which may be them same as System.lineSeparator()
.
The exception due to:
- The first time call to makeLineHighlight
, by this line of code bufferText+="<li style=\"background-color: #EA2A40\">\n "+linesOfText[i+1]+"\n</li>\n";
, The line number of text is increase. On of them (new lines) is <li style="background-color: #EA2A40">
- The second time call to makeLineHighlight
, your new HTML has wrong format. Likes this:
<li style="background-color: #EA2A40">
<li style="background-color: #EA2A40">
</li>
So, a possible solution is using <br />
instead of System.lineSeparator()
, and another is avoid using \n
in your new HTML code.
Be aware that <br />
is also written as <br/>
or <br>
...
Upvotes: 0