如何在jTextArea中为所选文本设置字体颜色? [英] How to set font color for selected text in jTextArea?

查看:661
本文介绍了如何在jTextArea中为所选文本设置字体颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须为jTextArea中的选定文本设置定义的颜色(如红色).就像在文本区域(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.

如果有解决方案,我可以将jTextArea更改为jTextPane或JEditorPane.

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

推荐答案

带样式的文本(具有用于字符的颜色属性)可以作为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.

这篇关于如何在jTextArea中为所选文本设置字体颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆