1

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.

Aryan G
  • 1,281
  • 10
  • 30
  • 51

2 Answers2

4

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.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • Thank you, I think this code works. How to use StyledDocument and other style in it? it is showing "Can not find symbol". – Aryan G May 28 '13 at 11:54
  • 1
    There must be a JTextPane textPane, and `import javax.swing.text.*`. And then there is somewhere JButton with addActionListener or so. – Joop Eggen May 28 '13 at 12:09
1

First of all you can not do this using JTextArea because it is a plain text area.You have to use a styled text area like JEditorPane.see here.You can use a HTMLDocument and do what you want.See here

Sanjaya Liyanage
  • 4,706
  • 9
  • 36
  • 50