2017-08-18 48 views
0

我正在使用JTextPane在Java中創建帶有語法高亮的文本編輯器。當我運行該程序時,我得到以下輸出: https://www.dropbox.com/s/kkce9xvtriujizy/Output.JPG?dl=0JTextPane語法高亮偏移不正確

我希望每個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()); 
     } 

} 

提前感謝!

回答

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()); 
     } 

} 

UPDATE:

的字符串是一個問題,但如果沒有它,還有一個偏移,可能是由於線路末端。所以,我已經找到了唯一的解決辦法是重新創建一個新的文件:

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); 
} 
+0

想這一點,但現在我的新的輸出看起來是這樣的: – JPadley

+0

https://www.dropbox.com/s/eb0dicxur99cr0w/newOutput.JPG ?dl = 0 – JPadley

+0

@JPadley對,對不起。新的更新。 –