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);
}
Целью приведенного выше фрагмента кода является изменение цвета конкретной строки кода между двумя индексами, от и до. После вызова этой функции текст и цвет в JTextPane
обновляются правильно (конкретная строка).
Однако, когда я пытаюсь обновить JTextPane
новыми текстами (путем очистки jtextpane
и повторного добавления нового текста), весь текст автоматически окрашивается в цвет, назначенный последним при вызове с помощью setJTextPaneFont
.
По сути, вместо нескольких цветных строк весь документ (новый) становится цветным, даже не вызывая функцию выше. Поэтому я подозреваю, что атрибуты JTextPane
каким-то образом изменились.
Итак, вопрос в том, как я могу сбросить JTextPane
обратно к атрибутам по умолчанию?