2014-03-29 23 views
0

我试图在NetBeans中实现一个文本编辑器,它具有简单的功能:文本样式(粗体,斜体,带下划线的),打开文件,保存文件和搜索。搜索功能在文档中搜索指定的字符串并突出显示结果。当我试图删除这些高亮或为不同的搜索添加新的亮点时会出现问题。目前我使用StyledDocument对象和jTextPane。NetBeans中的文本编辑器

private void textHighlight(int startAt, int endAt, Color c) { 
    Style sCh; 
    sCh = textEditor.addStyle("TextBackground", null); 
    StyleConstants.setBackground(sCh, c);     
    StyledDocument sDoc = textEditor.getStyledDocument(); 
    sDoc.setCharacterAttributes(startAt, endAt - startAt, sCh, false); 
} 

private void textFind(java.awt.event.ActionEvent evt) { 
    int searchIndex = 0;       
    String searchValue = searchField.getText(); 
     if(lastIndex != -1) { 
      while(searchIndex < lastIndex) { 
       countOccurencies++; 
       int i = textEditor.getText().indexOf(searchValue, searchIndex);     
       textHighlight(i, i+searchValue.length(), Color.MAGENTA); 
       searchIndex = i+searchValue.length(); 
      } 
      statusLabel.setText(countOccurencies + " rezultatov."); 
     } else { 
      statusLabel.setText("Ni rezultatov!"); 
     } 
    } 
} 

private void searchEnd(java.awt.event.ActionEvent evt) { 
    textEditor.removeStyle("TextBackground"); 
} 

removeStyle()似乎没有工作。

回答

2

必须承认我不知道样式是如何工作的,但是在添加样式时样式的属性可能会复制到文档中?

另一种选择是使用Highlighter类。请参阅textPane.getHighlighter()。然后,您可以跟踪您添加到ArrayList中的各个高光,然后使用ArrayList删除亮点,以便清除文本平移。

而且,你的搜索循环中,你有几个问题:

  1. 不要使用的getText()方法。这可能会导致文本偏移在文本窗格中的每行文本中都会被忽略。有关更多信息和解决方案,请参阅Text and New Lines

  2. 您正在获取循环内的文本,效率不高。你只能在循环之外获得文本。

+0

我试图在替换函数中使用getDocument()。getText()方法,但是当替换长度与原始文本长度不同时,它给了我一个偏移量。 – user3476140

+0

@ user3476140,不确定你在说什么。这个问题是关于突出显示文字,而不是取代文字。我给了你一个链接阅读,我不能更好地解释这个概念。 – camickr