Claudiu M Claudiu M - 23 days ago 11
Java Question

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
.

Answer

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)