如何在JEditorPane中解决此问题

时间:2019-06-11 21:16:22

标签: java swing 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);

    }

1 个答案:

答案 0 :(得分:0)

您输入的文本为HTML/CSS。请注意,HTML中的换行符是<br />,而不是System.lineSeparator(),并且您在新的HTML代码中使用了\n,这可能与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(),另一种方法是避免在新的HTML代码中使用\n

请注意,<br />也被写为<br/><br> ...