I'm making a little Notepad program because I am very bored and thought I would try to implement a "Find" feature within my program.
I want to highlight every word that matches a given string.
here is the main chunk of code
if(e.getSource() == m_find){
String s = (String)JOptionPane.showInputDialog("Find Word", "Please search a word");
if(m_area.getText().contains(s)){
int start = m_area.getText().indexOf(s);
int length = start + s.length();
try {
highlight.addHighlight(start, length, painter);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
This only gets the first occurrence of the word, how would I be able to high every occurrence of the word.
I'm sure there are many ways, but one would be to use a while
loop to keep highlighting occurrences if there are more to find. Then you would only keep looking at the String past what you already highlighted.
String stringToFindWordsIn = m_area.getText();
while(stringToFindWordsIn.contains(s)){
// highlight the word
// Make stringToFindWordsIn the substring from where you just highlighted to the end (drop off everything before and including the word you just highlighted)
}
You can use indexOf
with start parameter to start searching form given index, example implementation:
int start = 0;
do {
start = m_area.getText().indexOf(s, start);
int length = start + s.length();
try {
highlight.addHighlight(start, length, painter);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
start += length;
}
Try this:
if(e.getSource() == m_find){
String s = (String)JOptionPane.showInputDialog("Find Word", "Please search a word");
if(m_area.getText().contains(s)){
String text = m_area.getText();
int start = text.indexOf(s);
while (start >= 0) {
int length = start + s.length();
try {
highlight.addHighlight(start, length, painter);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
start = text.indexOf(s, start + 1);
}
}
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.