I have a problem with some code I have written to go through the text in a JTextPane and highlight key words ("hello")
it works fine, unless I delete a character off of one of the highlighted words, then it doesn't update the styles anymore... here is my code:
public class ScriptEditor extends JFrame
{
private static final long serialVersionUID = 1L;
private static int height = 340;
private static int width = 675;
private boolean saved = false;
public Pattern matcher = Pattern.compile("hello");
private JTextPane editor = new JTextPane();
public ScriptEditor()
{
super("Script Editor");
setJMenuBar(new ScriptMenu());
setSize(width, height);
editor.getDocument().addDocumentListener(new DocumentListener()
{
public void changedUpdate(DocumentEvent event) {}
public void insertUpdate(DocumentEvent event)
{
checkForHighlights();
}
public void removeUpdate(DocumentEvent event)
{
checkForHighlights();
}
});
add(new JScrollPane(editor));
}
private void checkForHighlights()
{
Runnable checker = new Runnable()
{
public void run()
{
Matcher stringMatcher;
try
{
stringMatcher = matcher.matcher(editor.getDocument().getText(0, editor.getDocument().getLength()));
StyleContext style = StyleContext.getDefaultStyleContext();
AttributeSet black = style.addAttribute(style.getEmptySet(), StyleConstants.Foreground, Color.BLACK);
AttributeSet red = style.addAttribute(style.getEmptySet(), StyleConstants.Foreground, Color.RED);
editor.getStyledDocument().setCharacterAttributes(editor.getDocument().getLength(), editor.getDocument().getLength(), style.getEmptySet(), true);
while (stringMatcher.find())
{
editor.getStyledDocument().setCharacterAttributes(stringMatcher.start(), stringMatcher.end() - stringMatcher.start(), red, false);
}
}
catch (BadLocationException e)
{
e.printStackTrace();
}
}
};
SwingUtilities.invokeLater(checker);
}
this is the sequence of events in testing:
type: "hello" (result is red highlight) type: " world" (result is red highlight round hello and black for " world" type: "hello" (result is read highlight, as expected) type: space and then delete, or just delete (no change) type: test (result is test is highlighted red!!!)
picture:
can anybody tell me what I am doing wrong here? How can I fix this!?
Thanks