Hello everyone!
In my program I use a JEditorPane and HTML to display a set of records retrieved from a database in a Web-like enviroment, similar to a google result page. I want to let the user search text in the result page so that he or she can locate a certain result more quickly.
To do so i extract the text from the JEditorPane and permor a search in it with the indexOf function of the String class once the location of the String is returned I try to use the Highlighter of the JEditorPane to highlight the text but it doesn't work and I don't understand why.
I have been looking around the web but most of the examples I have found are using JEditorPane as a plain text or rich text none is using the JEditorPane as an HTML display. What I was wondering is...
Is it possible to highlight text in a JEditorPane that is displaying HTML? and How do you do it?
Here's my code:
public void findInPage(JEditorPane page, String sText)
{
int offset;
int startPos;
int sTextLenght;
Highlighter hliter;
int pageTextLength;
String pageText = null;
if(page == null || sText == null) return;
sTextLenght = sText.length();
try
{
pageTextLength = page.getDocument().getLength();
if(pageTextLength < 1) return;
pageText = page.getDocument().getText(0, pageTextLength);
}
catch(BadLocationException ex)
{
// Bad location?
System.out.println(ex);
return;
}
if(pageText == null) return;
startPos = 0;
if(lastSearchPage == page && lastSearchText.equals(sText))
if(lastLocateIndex >= 0)
startPos = lastLocateIndex + 1;
System.out.println(sText + " starting at: " + startPos);
offset = pageText.indexOf(sText, startPos);
if(offset < 0)
{
JOptionPane.showMessageDialog(null, "Text not found", "Find in results", JOptionPane.INFORMATION_MESSAGE);
lastSearchPage = page;
lastSearchText = sText;
lastLocateIndex = -1;
}
else
{
hliter = page.getHighlighter();
hliter.removeAllHighlights();
try
{
hliter.addHighlight(offset, sTextLenght, myHighlightPainter);
}
catch(Exception ex)
{
System.out.println(ex);
}
lastSearchPage = page;
lastSearchText = sText;
lastLocateIndex = offset;
}
}
// An instance of the private subclass of the default highlight painter
Highlighter.HighlightPainter myHighlightPainter = new MyHighlightPainter(Color.red);
// A private subclass of the default highlight painter
class MyHighlightPainter extends DefaultHighlighter.DefaultHighlightPainter {
public MyHighlightPainter(Color color) {
super(color);
}
}
The last few lines are from an example i found on the internet.
Am I doing something wrong?
Thanks in advance.