【问题标题】:How to change the color of text between two positions?如何更改两个位置之间的文本颜色?
【发布时间】:2016-03-02 22:20:31
【问题描述】:

我想在突出显示时从两点更改我的 Swing 应用程序 (JTextPane) 的文本颜色。如果用户突出显示索引 4 到 9 中的短语,那么只有这些字符会永久更改其颜色。我说永久是因为我已经知道有一个setSelectionColor() 选项,但这只是暂时的。我已经设法获得了突出显示文本的起点和终点,但我走到了死胡同。

这是我目前所拥有的:

StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet attributes = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, color);

    if(tp.getSelectedText() != null){//tp is a jtextpane. text is highlighted. change highlighted text color
        int start = tp.getSelectionStart();
        int end = tp.getSelectionEnd();
        //update the color of the text within start and end
    }
tp.setCharacterAttributes(attributes, false);//update the color for the new text

【问题讨论】:

    标签: java swing colors highlight


    【解决方案1】:

    我已经设法获得了突出显示文本的起点和终点,

    您可以使用以下内容设置文本的属性:

    //  Define a keyword attribute
    
    SimpleAttributeSet keyWord = new SimpleAttributeSet();
    StyleConstants.setForeground(keyWord, Color.RED);
    StyleConstants.setBackground(keyWord, Color.YELLOW);
    StyleConstants.setUnderline(keyWord, Boolean.TRUE );
    StyleConstants.setBold(keyWord, true);
    
    //  Change attributes on some text
    
    StyledDocument doc = textPane.getStyledDocument();
    doc.setCharacterAttributes(start, end - start, keyWord, false);
    

    您还可以使用StyledEditorKit 操作来设置文本样式(粗体、斜体、颜色...)。阅读 Text Component Features 上的 Swing 教程部分,了解更多信息和工作示例。

    【讨论】:

    • 谢谢!文本突出显示后如何返回原始字体颜色?如何获取文本的当前字体颜色?我想我会用它来恢复以前的字体颜色,在为突出显示文本着色之后。
    • @swagantiswag,使用空的SimpleAttributeSet。阅读 API 以获取正确的参数。
    猜你喜欢
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 2023-03-07
    相关资源
    最近更新 更多