I’m looking for a quick way to find a String in a JTextPane and change the style there, so it gets highlighted. What I currently have is something like this (tpOutput is the JTextPane in question, strSearch the String to be searched.. duh):
int index = tpOutput.getText().indexOf(strSearch);
StyledDocument doc = tpOutput.getStyledDocument();
doc.setCharacterAttributes(i, strSearch.length(), doc.getStyle("exampleStyle") , false);
However, as beautiful as that would be if it worked, it counts wrong on newline characters, so if I search the text “foobar” in
foobarTTT
abcd123
abcd123
it would highlight “foobar” in the first line correctly. However, in
abcd123
abcd123
foobarTTT
it would highlight “obarTT” (and the following 2 whitespaces if they exist)
I’m probably doing the whole thing wrong, trying to get the offset easy using just the text. Anyone know the proper way to do this?
You can also use a
Highlighter, discussed in How to Use Text Fields: Another Example: TextFieldDemo.