我有一個TextArea
其中包含一個文檔。我實施了DocumentListener
以突出顯示與TextField
相匹配的單詞。HighLighting all matches words Java
此代碼所做的是突出顯示我單個單詞而不是所有匹配。即:如果我嘗試在TextArea
,&中搜索單詞「移動」,則該單詞重複3次,此代碼僅突出顯示第一個單詞而沒有其他單詞,我需要突出顯示匹配的所有單詞!
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();
}
您搜索一次,您爲什麼期望它找到多個匹配? – Idos
根據你的代碼,它只會顯示第一次出現,更多你需要通過匹配其他索引來獲得其他索引 – Vickyexpert
https://shekhargulati.com/2010/05/04/finding-all-the-indexes-of-a-整個詞在給定字符串使用java /和http://stackoverflow.com/questions/13326872/how-to-get-the-positions-of-all-matches-in-a-string – Idos