首页 > 解决方案 > 如何在 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);

    }

标签: javaswingjeditorpane

解决方案


您的输入文本是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>...


推荐阅读