Claudiu M Claudiu M - 1 year ago 145
Java Question

Java Swing, iterate through text Area

I want to find the word occurrence in text area, so each time I press

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.

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) {

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

Answer Source

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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download