Hi.
I write a piece of code to highlight word in the TextEditorPane,according to
http://java.sun.com/docs/books/tutorial/uiswing/components/text.html
Here is my code.
...
String keyword[]={"word","word1"};
Document doc = jTextPane.getDocument();
int beginindex = 0;
String str = doc.getText(0, doc.getLength());
for (int i = 0; i < keyword.length; i++) {
for (int j = 0; j < str.length(); j++) {
beginindex = str.indexOf(keyword[i], j);// locate the keyword
if ( -1 != beginindex) {// if keyword exist
doc.remove(beginindex, keyword[i].length());// remove the
keyword from the doc
/*
problem is here.
I remove the keyword from the doc(Document Object).
And insert the keyword with highlight style to the doc.
It takes a lot of time to do this.(It makes my application
slow)
Also,
if the content in the doc is too long, this piece of code
will cause overflow.
(because the limitation of int is 65535)
Re:Is there any good solution to do this?
*/
doc.insertString(beginindex, keyword[i],
jTextPane.getStyle(this._s_light_keyword));//
add the style to the keyword and insert it to its original position
j = beginindex + keyword[i].length();
}
}
}
...
Thank you for you help.
ByteCoder - 21 May 2005 15:23 GMT
> Hi.
>
[quoted text clipped - 3 lines]
>
> Here is my code.
[...]
Please don't cross-post this to all the Java groups. Most people who are
into Java are subscribed to all of the common Java newsgroups.

Signature
-------------
- ByteCoder - ...I see stupid people
-------------
Curiosity *Skilled* the cat
Christian Kaufhold - 21 May 2005 16:37 GMT
> Document doc = jTextPane.getDocument();
StyledDocument doc = jTextPane.getStyledDocument();
> int beginindex = 0;
> String str = doc.getText(0, doc.getLength());
[quoted text clipped - 3 lines]
>
> if ( -1 != beginindex) {// if keyword exist
There is no need to remove/add the text to change the attributes.
doc.setCharacterAttributes(beginindex, beginindex + keyword[i].length(), jTextPane.getStyle(this._s_light_keyword), true);
Usage of Document Styles for character attributes is misleading as they
will not be updated.
> Also,
> if the content in the doc is too long, this piece of code
> will cause overflow.
> (because the limitation of int is 65535)
Eh? int is signed 32 bits.
> add the style to the keyword and insert it to its original position
> j = beginindex + keyword[i].length();
> }
> }
> }
Christian