简体   繁体   中英

Java Swing, iterate through text Area

I want to find the word occurrence in text area, so each time I press button it will search for next occurrence of specified word, just like Ctrl+F does. Does anyone know how can I do that? This is the code that finds only 1st occurrence of given word.

@Override
public void actionPerformed(ActionEvent arg0) {
    if (button == arg0.getSource()) {
        int index = textArea.getText().indexOf(find.getText());
        int len = find.getText().length();
        Highlighter.HighlightPainter highlight = new DefaultHighlighter.DefaultHighlightPainter(Color.BLACK);
        try {
            textArea.getHighlighter().addHighlight(index, index + len, highlight);
        } 
        catch (BadLocationException e) {
            e.printStackTrace();
        }
    }
}

textArea is the text area where I have words, and find is the text field where I search for a specific word in textArea .

Save index of previous occurance as field and use two argument indexOf method, which takes String and startIndex as arguments.

ETA: public int indexOf(String str, int fromIndex)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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