如何更改两个位置之间的文本颜色?
How to change the color of text between two positions?
我想在突出显示时从两点更改我的 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
I have managed to get the starting and ending points of the highlighted 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
操作来风格化文本(粗体、斜体、颜色...)。阅读有关 Text Component Features 的 Swing 教程部分,了解更多信息和工作示例。
我想在突出显示时从两点更改我的 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
I have managed to get the starting and ending points of the highlighted 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
操作来风格化文本(粗体、斜体、颜色...)。阅读有关 Text Component Features 的 Swing 教程部分,了解更多信息和工作示例。