I'm trying to create a JTextPane that has the following properties:

  1. Vowel letters are colored in green
  2. Consonants are colored in blue
  3. Numbers are colored in red
  4. And the maximum number of characters is 26 and all characters are in Upper Case
    To achieve this I used DocumentListener and DocumentFilter classes and the texts are getting colored but not properly.For example, when I started the program and type 'VOWEL' V is painted in black, O - in blue, W - in blue, E - in blue and L - in Green. But that's not how I wanted it to worked, it should have colored 'E' and 'L' in green and the rest in blue. So what is the problem with my code. Here is the part of my code that handles the insertUpdate

    public void insertUpdate(DocumentEvent e) {

        String inserted = "";
        try{
            inserted = doc.getText(e.getOffset(), 1);
        if(isVowel(inserted.toLowerCase()))//isVowel() is a method that returns true if the string is a vowel
        {
            setCharacterAttributes( vowelSet, false);
            label.setText(inserted + "  " + "offset: " + e.getOffset());
        }
        else if(isNumber(inserted) != null)//isNumber() is a method that returns an int if it is an int character or null otherwise
        {
            setCharacterAttributes(numberSet,false);
        }
        else{
            setCharacterAttributes(consonantSet, false);
            label.setText(inserted + "  " + doc.getLength());}
    }
    
        catch (BadLocationException bde){ bde.getMessage();}
    }
    

Hi,

Yous are applying the style "on the next letter" not "the last letter", and that's why you have the style is "applyed late".

So, you must use the other setCharacterAttributes :

Click Here

Thanks I solved the problem. You are right, I should have used the setCharacterAttributes method in DefaultStyledDocument. But that also could raise an IllegalStateException if it is called from the DocumentListener methods because it(DocumentListener) doesn't have the writeLock and readLock to modify the text pane.

This question has already been answered. Start a new discussion instead.