Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在两个位置之间更改文本的颜色?_Java_Swing_Colors_Highlight - Fatal编程技术网

Java 如何在两个位置之间更改文本的颜色?

Java 如何在两个位置之间更改文本的颜色?,java,swing,colors,highlight,Java,Swing,Colors,Highlight,我想在突出显示时从两点更改Swing应用程序(JTextPane)文本的颜色。如果用户突出显示从索引4到索引9的短语,则只有这些字符将永久更改其颜色。我说永久是因为我已经知道有一个setSelectionColor()选项,但这只是暂时的。我已经找到了突出显示文本的起点和终点,但我已经到了死胡同 以下是我到目前为止的情况: StyleContext sc = StyleContext.getDefaultStyleContext(); AttributeSet attributes = sc.a

我想在突出显示时从两点更改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
我已经找到了突出显示文本的起点和终点

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

//  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
操作设置文本样式(粗体、斜体、彩色…)。有关更多信息和工作示例,请阅读上Swing教程的部分

我已经找到了突出显示文本的起点和终点

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

//  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
操作设置文本样式(粗体、斜体、彩色…)。有关更多信息和工作示例,请阅读上的Swing教程部分。

谢谢!文本高亮显示后,如何返回到原始字体颜色?如何获取文本的当前字体颜色?我想在给突出显示的文本着色后,我会使用它恢复到以前的字体颜色。@swagantiswag,使用空的
SimpleAttributeSet
。请阅读API以了解正确的参数。谢谢!文本高亮显示后,如何返回到原始字体颜色?如何获取文本的当前字体颜色?我想在给突出显示的文本着色后,我会使用它恢复到以前的字体颜色。@swagantiswag,使用空的
SimpleAttributeSet
。请阅读API以了解正确的参数。