• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1544
  • Last Modified:

Different font colors in JTextPane

I'm inserting different lines into a JTextPane using the StyledDocument.insertString() and I am wondering how to make the different lines of text different colors. This should be fairly simple, any help is appreciated.

import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;

public class MyTextPanel extends JPanel{
    JTextPane jtp = new JTextPane();

    public MyTextPanel(){
       super(new BorderLayout());
       this.add(jtp, BorderLayout.CENTER);
       StyledDocument sd = jtp.getStyledDocument();
       sd.insertString(sd.getLength(), "First Text\n", null);
       //color change code here
       sd.insertString(sd.getLength(), "Text in a different Color", null);
       //color change again
       sd.insertString(sd.getLength(), "Text in a third Color", null);


1 Solution
you'll have to play with text attributes.
kylarAuthor Commented:
Thanks, that was just what I needed.

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now