突出显示偏移的JTextPane语法不正确

时间:2017-08-18 09:25:52

标签: java html jtextpane

我正在使用JTextPane在Java中创建一个带有语法突出显示的文本编辑器。当我运行程序时,我得到这个输出: https://www.dropbox.com/s/kkce9xvtriujizy/Output.JPG?dl=0

我希望每个HTML标记都以粉红色突出显示,但在几个标记后,它会突出显示错误的区域。

以下是突出显示的代码:

    private void htmlHighlight() {
    String textToScan;
        textToScan = txtrEdit.getText();
        StyledDocument doc = txtrEdit.getStyledDocument(); 
        SimpleAttributeSet sas = new SimpleAttributeSet();
        while(textToScan.contains(">")) {
            StyleConstants.setForeground(sas, new Color(0xEB13B1));
            StyleConstants.setBold(sas, true);
            doc.setCharacterAttributes(textToScan.indexOf('<'), textToScan.indexOf('>'), sas, false);
            StyleConstants.setForeground(sas, Color.BLACK);
            StyleConstants.setBold(sas, false);
            textToScan = textToScan.substring(textToScan.indexOf('>') + 1, textToScan.length());
        }

}

提前致谢!

1 个答案:

答案 0 :(得分:0)

setCharacterAttributes的第二个参数是长度,而不是结束索引。

这给了我们:

    private void htmlHighlight() {
    String textToScan;
        textToScan = txtrEdit.getText();
        StyledDocument doc = txtrEdit.getStyledDocument(); 
        SimpleAttributeSet sas = new SimpleAttributeSet();
        while(textToScan.contains(">")) {
            StyleConstants.setForeground(sas, new Color(0xEB13B1));
            StyleConstants.setBold(sas, true);
            int start = textToScan.indexOf('<');
            int end = textToScan.indexOf('>')+1;
            doc.setCharacterAttributes(start, end-start, sas, false);
            textToScan = textToScan.substring(textToScan.indexOf('>') + 1, textToScan.length());
        }

}

更新:

子串是一个问题,但没有它,仍然有一个偏移,可能是由于行的结束。所以我找到的唯一解决方案是重新创建一个新文档:

try {
    String textToScan;
    textToScan = txtrEdit.getText();
    StyledDocument doc = new DefaultStyledDocument();
    SimpleAttributeSet sas = new SimpleAttributeSet();
    StyleConstants.setForeground(sas, new Color(0xEB13B1));
    StyleConstants.setBold(sas, true);
    int end = 0;
    while (true) {
        int start = textToScan.indexOf('<', end);
        if (start < 0) {
            doc.insertString(end, textToScan.substring(end), null);
            break;
        }
        doc.insertString(end, textToScan.substring(end, start), null);
        end = textToScan.indexOf('>', start+1);
        if (end < 0) {
            doc.insertString(start, textToScan.substring(start), sas);
            break;
        }
        ++end;
        doc.insertString(start, textToScan.substring(start, end), sas);
    }
    txtrEdit.setStyledDocument(doc);
} catch (BadLocationException ex) {
    Logger.getLogger(MyDialog.class.getName()).log(Level.SEVERE, null, ex);
}