java - 如何在 JEditorPane 中解决此问题
问题描述
我尝试在 JEditorPane 的文本中添加一些 HTML/CSS。setText()
此类中的方法也被覆盖。
当我在窗格中插入超过 14 行然后在窗格的文本上运行makeLineHighlight()
或运行makeLineHighlight()
两次时,某些行会被删除或出现一些异常。当窗格的文本更改时(我在循环中检查它),然后我使用覆盖setText()
在窗格中创建一个数字列表。
当我删除super.setText()
代码时,它可以正常工作。
@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);
}
解决方案
您的输入文本是HTML/CSS
. 请注意,HTML 中的换行符是<br />
,而不是System.lineSeparator()
您\n
在新的 HTML 代码中使用的换行符,它们可能与System.lineSeparator()
.
由于以下原因导致的异常:
- 第一次调用makeLineHighlight
,通过这行代码bufferText+="<li style=\"background-color: #EA2A40\">\n "+linesOfText[i+1]+"\n</li>\n";
,文本的行数增加了。其中(新行)是<li style="background-color: #EA2A40">
- 第二次调用makeLineHighlight
,您的新 HTML 格式错误。喜欢这个:
<li style="background-color: #EA2A40">
<li style="background-color: #EA2A40">
</li>
因此,一个可能的解决方案是使用<br />
而不是System.lineSeparator()
,另一个是避免\n
在您的新 HTML 代码中使用。
请注意,<br />
它也写为<br/>
或<br>
...
推荐阅读
- mysql - INSERT 语句出错:“VALUE 在此位置无效”
- sql - SQL - 如何使用 CASE 表达式查询 VIEW - 查找列中的平均数
- c - 如果 flag = 0,那么哪个语句是执行 true 或 false 块的最可取的语句?if(!flag) 或 if(flag == 0)
- sql - 使用 T-SQL 从存储过程中仅获取一列
- blockchain - 如何在没有元掩码的情况下创建 DAPP
- spring-boot - SpringBoot @RequiredArgsConstructor(onConstructor = @__(@Autowired)) 循环依赖错误
- mysql - SQL 格式化为“用户友好的日期”
- node.js - 为什么我的 Node 包和 CLI 命令无法识别?
- django - 在 django rest 框架中聚合结果
- c - 尽管 scanf 不满足条件,但循环不会终止