Search code examples
javastringswingcolorsjtextarea

Coloring a string before adding it to a JTextArea


Is there a way, to highlight or change the color of a string that gets added from a String[] to a JTextArea? Currently I'm using the DefaultHighlighter with the addHighlighter(from, to, highlighter) method, but that does not work the way ' want it to. The String[] comes from a list that records key imput, and ' want every singlecharacter string to be highlighted to colored.

Example what the JTextArea looks like: A B C D E F G [SPACE] H I J K L [ENTER].

By the way, I add one string at a time to the textArea with a for loop like that:

for(int cnt = 0; cnt <= strings.length; cnt++){

        if(strings[cnt].length() != 1){
            text.append("[" + strings[cnt] + "] ");
        }
        else{
            text.append(strings[cnt]);
                //tryed to do it like that, but obviously did not work the way it wanted it to

// text.getHighlighter().addHighlight(cnt, cnt + 1, highlightPainter); } }


Solution

  • The color for a JTextArea applys to the entire JTextComponent's Document text foreground color rather than to individual characters. You can use JTextPane instead

    Here is a simple example:

    enter image description here

    public class ColoredTextApp {
    
        public static void main(String[] args) {
    
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    JFrame frame = new JFrame("Colored Text");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
                    StyledDocument doc = new DefaultStyledDocument();
                    JTextPane textPane = new JTextPane(doc);
                    textPane.setText("Different Colored Text");
    
                    Random random = new Random();
                    for (int i = 0; i < textPane.getDocument().getLength(); i++) {
                        SimpleAttributeSet set = new SimpleAttributeSet();
                        StyleConstants.setForeground(set,
                                new Color(random.nextInt(256), random.nextInt(256),
                                        random.nextInt(256)));
                        StyleConstants.setFontSize(set, random.nextInt(12) + 12);
                        StyleConstants.setBold(set, random.nextBoolean());
                        doc.setCharacterAttributes(i, 1, set, true);
                    }
    
                    frame.add(new JScrollPane(textPane));
                    frame.pack();
                    frame.setVisible(true);
                }
            });
        }
    }