Search code examples
javacolorsjeditorpane

JEditorKit color single chars without html


I want to mark parts of a jeditorpane content with a color, without using the html type content type. is there a way to accomplish this, maybe playing around with the document?


Solution

  • without using the html type content type

    This means you have a plan text file and you should be using a JTextPane. Then you can use attributes to color the text.

    JTextPane textPane = new JTextPane();
    textPane.setText("Some text for the text pane.");
    StyledDocument doc = textPane.getStyledDocument();
    
    SimpleAttributeSet keyWord = new SimpleAttributeSet();
    StyleConstants.setForeground(keyWord, Color.RED);
    StyleConstants.setBackground(keyWord, Color.YELLOW);
    StyleConstants.setBold(keyWord, true);
    
    // Color existing text
    
    doc.setCharacterAttributes(0, 5, keyWord, false);
    
    // Add some text
    
    try
    {
        doc.insertString(doc.getLength(), "\nEnd of text", keyWord );
    }
    catch(Exception e) { System.out.println(e); }