Search code examples
javajtextarea

How to set font color for selected text in jTextArea?


I have to set defined color(like red) for selected text in jTextArea. It is like highlighting process in text area (jTextArea). When I select particular text and click on any button it should change in predefined color.

I can change jTextArea to jTextPane or JEditorPane if there is any solution.


Solution

  • Styled text (with a color attribute for characters) is available as StyledDocument, and usable in JTextPane and JEditorPane. So use a JTextPane.

    private void buttonActionPerformed(java.awt.event.ActionEvent evt) {
        StyledDocument doc = textPane.getStyledDocument();
        int start = textPane.getSelectionStart();
        int end = textPane.getSelectionEnd();
        if (start == end) { // No selection, cursor position.
            return;
        }
        if (start > end) { // Backwards selection?
            int life = start;
            start = end;
            end = life;
        }
        Style style = textPane.addStyle("MyHilite", null);
        StyleConstants.setForeground(style, Color.GREEN.darker());
        //style = textPane.getStyle("MyHilite");
        doc.setCharacterAttributes(start, end - start, style, false);
    }                                      
    

    Mind: the style can be set at the creation of the JTextPane, and as the outcommented code shows, retrieved out of the JTextPane field.