J'ai un TextArea
qui contient un document. J'ai mis en place un DocumentListener
afin de mettre en évidence les mots qui correspondent dans le TextField
.HighLighting tous les mots de correspondance Java
Ce code fait ressortir un mot unique au lieu de tous les mots. i.e: si j'essaie de rechercher le mot "déplacer" dans le TextArea
, & il y a répété 3 fois ce mot, ce code vient mettre en évidence le premier et pas le reste, je dois mettre en évidence tous les mots qui correspond!
public void search() throws BadLocationException //This method makes all logic for highLigh from jtextField into Document(TextArea)
{
highLighter.removeAllHighlights();
String s = textField.getText();
if(s.length() <= 0)
{
labelMessage("Nothing to search for..");
return; //go out from this "if statement!".
}
String content = textArea.getText();
int index = content.indexOf(s, 0); //"s" = the whole document, 0 = means that was found(match) or -1 if no match(no found is return -1)
if(index >= 0) //match found
{
int end = index + s.length();
highLighter.addHighlight(index, end, highlighterPainter);
textArea.setCaretPosition(end);
textField.setBackground(entryBgColor);
labelMessage("'" + s + "' found. Press ESC to end search");
}
}
void labelMessage(String msm)
{
statusLabel.setText(msm);
}
@Override
public void changedUpdate(DocumentEvent e)
{
// TODO Auto-generated method stub
}
@Override
public void insertUpdate(DocumentEvent e)
{
try
{
search();
} catch (BadLocationException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
Vous recherchez une fois, pourquoi attendez-vous qu'il trouve plusieurs correspondances? – Idos
Selon votre code il montrera seulement la première occurrence, pour plus vous devez obtenir d'autres index en faisant correspondre d'autres – Vickyexpert
https://shekhargulati.com/2010/05/04/finding-all-the-indexes-of-a- mot-entier-dans-un-donné-string-using-java/et http://stackoverflow.com/questions/13326872/how-to-get-the-positions-of-all-matches-in-a-string – Idos