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 обратно к атрибутам по умолчанию?


person jensiepoo    schedule 11.08.2014    source источник
comment
Чтобы быстрее получить помощь, опубликуйте MCVE (минимальный, полный, проверяемый пример).   -  person Andrew Thompson    schedule 11.08.2014
comment
Не уверен, что смогу сделать его менее сложным. Спасибо хоть.   -  person jensiepoo    schedule 11.08.2014
comment
Не уверен, что смогу сделать его менее сложным. Это не полное, не проверяемое и не пример.   -  person Andrew Thompson    schedule 11.08.2014
comment
Оцените комментарий.   -  person jensiepoo    schedule 11.08.2014
comment
Надеюсь, что это немного лучше. Пожалуйста, дайте мне знать, где я должен указать немного больше.   -  person jensiepoo    schedule 11.08.2014
comment
пожалуйста, где MCVE/SSCCE, действительно зависит от того, что содержит JTextPane, голосование за закрытие тоже   -  person mKorbel    schedule 11.08.2014


Ответы (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);
        }
person naveejr    schedule 11.08.2014
comment
не решает 3/4 потенциальных проблем с JTextPane (в ближайшем будущем) - person mKorbel; 11.08.2014

Проблема очистка jtextpane и повторного добавления нового текста может быть решена несколькими способами:

Вызовите doc.setCharacterAttributes(0, 1, attrs, true); и передайте здесь пустой AttributeSet

Пересоздайте документ и вместо doc.remove()/insert() вызовите jtp.setDocument(jtp.getEditorKit().createDefaultDocument())

Очистить входные атрибуты. Добавьте прослушиватель каретки и проверьте, пуст ли документ. Когда он станет пустым, удалите все нужные атрибуты.

person StanislavL    schedule 11.08.2014