Compton11 0 Light Poster

Hey all...I'm working on creating a text editor for one of my college projects. One of features I have to implement is a find and replace feature which requests the user to input a word to find and also input a word that will be used to replace that word to be found. So for instance, if the sentence in the JEditorPane was:

"Sally and John went to the supermarket to buy milk and eggs. After shopping, Sally took a nap and Sally woke up after 2 hours."

If the user inputed:
Find what: Sally
Replace with: Melissa

The resulting sentence should be:

"Melissa and John went to the supermarket to buy milk and eggs. After shopping, Melissa took a nap and Melissa woke up after 2 hours."

Of course I can implement this by just calling the replaceAll() method, but that only works for unformatted text. My text editor allows different font types, styles, color, etc, so when the text is replaced, the new text must retain the style format of the text it replaced. I looked up some info in the JavaDocs and found that we can use:

jEditPane.getDocument().remove(...);
jEditPane.getDocument().insertString(...);

I tried implementing this and tested the find and replace method with the above sentence, and the result was:

"Melissa and John went to the supermarket to buy milk and eggs. After shoppingMelissaly took a nap Melissaally woke up after 2 hours."

Here is my findAndReplace method:

private void findAndReplace(JTextComponent textComp, String pattern, String replacement){
        try {

            Document docs = textComp.getDocument();
            String text = docs.getText(0, docs.getLength());
            int pos = 0;
            int count = 0;
            
            //If the replace all occurrences is not selected, replace only the first instance
            if (!_jchbAll.isSelected()) {
                pos = text.indexOf(pattern, pos);
                _jepArea.getDocument().remove(pos, pattern.length());
                _jepArea.getDocument().insertString(pos, replacement, style);                
            } 
            //If replace all occurrences checkbox is selected, replace all the matches
            else if (_jchbAll.isSelected()) {
 
               //find all occurrences of the word and replace
               while ((pos = text.indexOf(pattern, pos)) >= 0) {                
                    _jepArea.getDocument().remove(pos, pattern.length());
                    _jepArea.getDocument().insertString(pos, replacement, style);
                    pos += replacement.length();
                }   
            }
            
        } catch (BadLocationException ex) {
            System.err.println(ex.getMessage());
        }
    }

Please try to help me! Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.