Im trying to make a highlighter that will highlight a word after I have typed it in a JTextArea. The problem I have, is that after I press space, the highlighter doesnt stop. It continues highlighting the next words as well.

public class highLighter {

    JTextArea ref;
    Highlighter hilite;
    String text;
    Document doc;
    public highLighter(JTextArea mainT) {
        ref = mainT;
        try {

        } catch (Exception ex) {
            Logger.getLogger(highLighter.class.getName()).log(Level.SEVERE, null, ex);

    public void light(int pos, int  lenght){
        hilite = ref.getHighlighter();
        doc = ref.getDocument();
        try {
            text = doc.getText(0, doc.getLength());
                // Create highlighter using private painter and apply around pattern
                hilite.addHighlight(pos, pos+lenght, myHighlightPainter);

        } catch (BadLocationException ex) {
            Logger.getLogger(highLighter.class.getName()).log(Level.SEVERE, null, ex);


Highlighter.HighlightPainter myHighlightPainter = new MyHighlightPainter(; 

 class MyHighlightPainter extends DefaultHighlighter.DefaultHighlightPainter {
    public MyHighlightPainter(Color color) {


I send a word in the text area's position and its length to the highlighter class as defined above. The code I use to send it to this class is hl.light(jTextArea1.getText().indexOf(word),word.length());

How do I make the highlighter stop after this word and only highlight a new word when it is called again?

Thanks in advance

Could you post the code where you are calling this method? its sounds to me like the problem would be there, since the highlightning is working, just not stopping.

String word ="";  
    private void jTextArea1KeyTyped(java.awt.event.KeyEvent evt) {                                    
       if (((int) evt.getKeyChar() == 32) || ((int) evt.getKeyChar() == 10) || ((int) evt.getKeyChar() == 9)) {
            word = "";
        } else {
            word += evt.getKeyChar();
        }        // TODO add your handling code here:

If I make the second parameter of light word.length-1 is stops fine, it just ignores the last letter of the word