javaswingnetbeansjtextpaneswing-highlighter

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. 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.

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.


Solution

  • 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. See 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.

    Also, inside your search loop you have a couple of problems:

    1. Don't use the getText() method. 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.