Search code examples
javaswingstylesjtextpane

How do I change the colour of certain words when they are entered into a JTextPane?


I've seen several posts on this, but none seem to work.

I have a thread on the Java Programming Forums about this, please help!: http://www.javaprogrammingforums.com/whats-wrong-my-code/47440-trying-make-simple-java-editor-having-trouble-changing-colour-words.html


Solution

  • 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 color
    StyleConstants.setForeground(style, Color.RED);
    // add some data to the document
    document.insertString(0, "", style);
    
    
    OR
    
    
    
    
    JTextPane pane = new JTextPane();
    SimpleAttributeSet set = new SimpleAttributeSet();
    StyleConstants.setForeground(set, Color.red);
    Document doc = pane.getStyledDocument();
    doc.insertString(doc.getLength(), "Kleine ", set);