Search code examples
javaswingjtextpane

How to change the color of specific words in a JTextPane?


How do I change the color of specific words in a JTextPane just while the user is typing? Should I override JTextPane paintComponent method?


Solution

  • Overwriting paintComponent will not help you.

    This is not an easy one, but not impossible either. Something like this will help you:

    DefaultStyledDocument document = new DefaultStyledDocument();
    JTextPane textpane = new JTextPane(document);
    StyleContext context = new StyleContext();
    // build a style
    Style style = context.addStyle("test", null);
    // set some style properties
    StyleConstants.setForeground(style, Color.BLUE);
    // add some data to the document
    document.insertString(0, "", style);
    

    You may need to tweak this, but at least it shows you where to start.