Как перекрасить цветной текст в JTextPane обратно в его цвет по умолчанию?
public void setJTextPane(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();
AttributeSet attrs = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);
// Set the font color
// 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, true);
}
public void recoverTextPane(JTextPane jtp, int from, int to) {
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet attrs = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground,
new Color(51,51,51));
StyledDocument doc = jtp.getStyledDocument();
doc.setCharacterAttributes(from, to, attrs, true);
}
Цель setJTextPane - нарисовать определенную линию JTextPane между двумя индексами. Функция работает правильно, как и ожидалось. Однако я хотел преобразовать эту конкретную строку текста обратно в ее исходный цвет. Поэтому я в основном создал отдельную функцию, которая преобразует эту строку в известный RGB. Однако это никак не влияет на текст. Кто-нибудь может диагностировать проблему с помощью кода?
Спасибо за помощь!!
1 ответ
SimplaAttributeSet attrs = new SimpleAttributeSet();
StyleConstants.setForeground(attrs, theColor);
StyledDocument doc = jtp.getStyledDocument();
doc.setCharacterAttributes(from, to, attrs, false);
Вы создаете пустой набор атрибутов, задаете цвет переднего плана и применяете его без замены исходных атрибутов. Проверить from
а также to
параметры для покрытия правильного фрагмента.