繁体   English   中英

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

[英]How to set font color for selected text in jTextArea?

我必须为jTextArea中的选定文本设置定义的颜色(如红色)。 就像在文本区域(jTextArea)中突出显示过程一样。 当我选择特定文本并单击任何按钮时,它应更改为预定义的颜色。

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

样式文本(具有字符的颜色属性)可以作为StyledDocument使用,并且可以在JTextPane和JEditorPane中使用。 因此,请使用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字段中检索。

首先,你不能做到这一点使用的JTextArea,因为它是一个纯文本area.You已使用像JEdi​​torPane.see一个样式的文本区域在这里 。你可以使用HTMLDocument的,做你want.See什么这里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM