简体   繁体   English

NetBeans中的文本编辑器

[英]Text editor in NetBeans

I am trying to implement a text editor in NetBeans with simple functions like: text styling (bold, italic, underlined ...), open file, save file and search. 我试图在NetBeans中使用简单的函数实现文本编辑器,如:文本样式(粗体,斜体,下划线...),打开文件,保存文件和搜索。 Search function searches for a specified string in the document and highlights the results. 搜索功能搜索文档中的指定字符串并突出显示结果。 The problem occurs when I am trying to remove those highlights or add new ones for different search. 当我尝试删除这些突出显示或为不同的搜索添加新的突出显示时,会出现此问题。 Currently I use StyledDocument object together with jTextPane. 目前我将StyledDocument对象与jTextPane一起使用。

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() doesn't seem to be working. removeStyle()似乎不起作用。

Must admit I don't know how Styles work, but maybe the attributes of the Style are copied to the Document at the time you add the Style? 必须承认我不知道样式是如何工作的,但是在添加样式时,样式的属性可能会复制到文档中?

Another option is to use the Highlighter class. 另一种选择是使用Highlighter类。 See textPane.getHighlighter(). 请参见textPane.getHighlighter()。 Then you can keep track of the individual highlights you add in an ArrayList and then use the ArrayList to remove the highlights when you want the clear the text pan. 然后,您可以跟踪在ArrayList中添加的各个高光,然后在需要清除文本平移时使用ArrayList删除高光。

Also, inside your search loop you have a couple of problems: 此外,在搜索循环中,您有几个问题:

  1. Don't use the getText() method. 不要使用getText()方法。 This can cause problems with text offsets being off by one for every line of text in the text pane. 对于文本窗格中的每行文本,这可能会导致文本偏移关闭一个问题。 See Text and New Lines for more information and the solution. 有关更多信息和解决方案,请参阅文本和新行

  2. You are getting the text inside the loop which is not very efficient. 你在循环中得到的文本不是很有效。 You should only get the text once outside the loop. 您应该只在循环外获取文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM