0

I'm making a little Notepad program because I am very bored and thought I would try to implement a "Find" feature within my program.

I want to highlight every word that matches a given string.

here is the main chunk of code

if(e.getSource() == m_find){
    String s = (String)JOptionPane.showInputDialog("Find Word", "Please search a word");
       if(m_area.getText().contains(s)){
         int start = m_area.getText().indexOf(s);
         int length = start + s.length();
           try {
               highlight.addHighlight(start, length, painter);
           } catch (BadLocationException e1) {
               e1.printStackTrace();
           }
    }

This only gets the first occurrence of the word, how would I be able to high every occurrence of the word.

3 Answers3

0

I'm sure there are many ways, but one would be to use a while loop to keep highlighting occurrences if there are more to find. Then you would only keep looking at the String past what you already highlighted.

String stringToFindWordsIn = m_area.getText();

while(stringToFindWordsIn.contains(s)){
    // highlight the word

    // Make stringToFindWordsIn the substring from where you just highlighted to the end (drop off everything before and including the word you just highlighted)
}
Andrew_CS
  • 2,542
  • 1
  • 18
  • 38
0

You can use indexOf with start parameter to start searching form given index, example implementation:

int start = 0;
do {
    start = m_area.getText().indexOf(s, start);
    int length = start + s.length();
    try {
        highlight.addHighlight(start, length, painter);
    } catch (BadLocationException e1) {
        e1.printStackTrace();
    }
    start += length;
}
Krzysztof Krasoń
  • 26,515
  • 16
  • 89
  • 115
0

Try this:

if(e.getSource() == m_find){
        String s = (String)JOptionPane.showInputDialog("Find Word", "Please search a word");
       if(m_area.getText().contains(s)){
         String text = m_area.getText();
         int start = text.indexOf(s);
         while (start >= 0) {
           int length = start + s.length();
           try {
               highlight.addHighlight(start, length, painter);
           } catch (BadLocationException e1) {
               e1.printStackTrace();
           }
           start = text.indexOf(s, start + 1);
        }
    }
Nguyen Tuan Anh
  • 1,036
  • 8
  • 14