Search code examples
javatextcolor

Coloring one character only in jTextPane


I am working on a project using netbeans. I am trying to color only one character located in multiple places of a text in jTextPane. I tried to use StyledDocument.setCharacterAttributes, but it allows me to color at least 2 characters, Which is not what I want.

For the moment I am using this code:

StyledDocument doc = jTextPane1.getStyledDocument();
javax.swing.text.Style style = jTextPane1.addStyle("Red", null);
StyleConstants.setForeground(style, Color.RED);
doc.setCharacterAttributes(5, 2, jTextPane1.getStyle("Red"), true); 

Can any one help to solve this problem.

Thank you in advance.


Solution

  • Here is an example of coloring a single character.

    import java.awt.Color;
    import javax.swing.*;
    import javax.swing.text.DefaultStyledDocument;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyledDocument;
    
    public class ColoredTextTest {
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    JFrame frame = initgui();
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.pack();
                    frame.setVisible(true);
                }
            });
        }
    
        private static JFrame initgui() {
            JFrame frame = new JFrame("Test");
            JPanel panel = new JPanel();
            StyledDocument doc = (StyledDocument) new DefaultStyledDocument();
            JTextPane textpane = new JTextPane(doc);
            textpane.setText("Test");
            javax.swing.text.Style style = textpane.addStyle("Red", null);
            StyleConstants.setForeground(style, Color.RED);
            doc.setCharacterAttributes(0, 1, textpane.getStyle("Red"), true); 
            panel.add(textpane);
            frame.add(panel);
            return frame;
        }
    }