public static void setJTextPaneFont(JTextPane jtp, Color c, int from, int to) {
// Start with the current input attributes for the JTextPane. This
// should ensure that we do not wipe out any existing attributes
// (such as alignment or other paragraph attributes) currently
// set on the text area.
MutableAttributeSet attrs = jtp.getInputAttributes();
// Set the font color
StyleConstants.setForeground(attrs, c);
// Retrieve the pane's document object
StyledDocument doc = jtp.getStyledDocument();
// Replace the style for the entire document. We exceed the length
// of the document by 1 so that text entered at the end of the
// document uses the attributes.
doc.setCharacterAttributes(from, to, attrs, false);
}
The purpose of the above piece of code is to change the color of a particular line of code between two indices, from and to. After the call to this function, the text and color in JTextPane
gets updated correctly(a particular line).
However, when I try to refresh the JTextPane
with new texts(by emptying the jtextpane
and re-appending new text), all text automatically gets painted into the color last assigned when called with setJTextPaneFont
.
Basically, instead of just having a few colored lines, the whole document(new one) becomes colored without ever making a call to the function above. Therefore I suspect that the attributes of JTextPane
somehow got modified.
So the question is, how would I be able to reset the JTextPane
back to default attributes?
Try this one
public void setJTextPaneFont(JTextPane jtp, Color c, int from, int to) {
// Start with the current input attributes for the JTextPane. This
// should ensure that we do not wipe out any existing attributes
// (such as alignment or other paragraph attributes) currently
// set on the text area.
StyleContext sc = StyleContext.getDefaultStyleContext();
// MutableAttributeSet attrs = jtp.getInputAttributes();
AttributeSet attrs = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);
// Set the font color
//StyleConstants.setForeground(attrs, c);
// Retrieve the pane's document object
StyledDocument doc = jtp.getStyledDocument();
// System.out.println(doc.getLength());
// Replace the style for the entire document. We exceed the length
// of the document by 1 so that text entered at the end of the
// document uses the attributes.
doc.setCharacterAttributes(from, to, attrs, true);
}