Reputation: 359
I want to change the color of my text for my Swing app (JTextPane) from two points, when highlighted. If the user highlights a phrase from, say, index 4 to 9, then only those characters will change their colors, permanently. I say permanently because I already know there is a setSelectionColor()
option, but that is only temporary. I have managed to get the starting and ending points of the highlighted text, but I've reached a dead end.
Here is what I have so far:
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
Upvotes: 0
Views: 207
Reputation: 324127
I have managed to get the starting and ending points of the highlighted text,
You can set the attributes of the text with something like:
// 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);
You can also use a StyledEditorKit
Action to stylize text (bold, italic, color...). Read the section from the Swing tutorial on Text Component Features for more information and working examples.
Upvotes: 4