且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在jTextArea中为所选文本设置字体颜色?

更新时间:2023-01-28 11:47:51

带样式的文本(具有用于字符的颜色属性)可以作为StyledDocument使用,并且可以在JTextPane和JEditorPane中使用.因此,请使用JTextPane.

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);
}                                      

注意:样式可以在创建JTextPane时设置,并且如注释后的代码所示,可以从JTextPane字段中获取.

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