Swing GUI, добавляющий цветной текст в JTextPane
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
вернуться к атрибутам по умолчанию?
2 ответа
Попробуй это
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);
}
Очистка jtextpane и повторное добавление новой текстовой проблемы могут быть решены несколькими способами:
Вызов doc.setCharacterAttributes(0, 1, attrs, true);
и передать пустой AttributeSet здесь
Воссоздать документ и вместо doc.remove()/insert()
вызов jtp.setDocument(jtp.getEditorKit().createDefaultDocument())
Очистить входные атрибуты. Добавьте слушатель каретки и проверьте, является ли документ пустым. Когда он пуст, удалите все нужные атрибуты.