Style ModStyle

final JTextPane textPane = new JTextPane();
ChangeListener changeListener = new ChangeListener() {
    public void stateChanged(ChangeEvent e) {
        reapplyStyles(textPane, (Style)e.getSource());
    }
};

// Make paragraph red
Style style = textPane.addStyle("Highlight", null);
style.addChangeListener(changeListener);
StyleConstants.setForeground(style, Color.red);
textPane.setParagraphAttributes(style, true);
// paragraph appears red

style = textPane.getStyle("Highlight");
StyleConstants.setUnderline(style, true);
// paragraph becomes red and underlined

// This method traverses every paragraph and content element
// and reapplies any style that matches the specified style
public static void reapplyStyles(JTextPane c, Style style) {
    // Get section element
    Element sectionElem = c.getDocument().getDefaultRootElement();

    // Get number of paragraphs.
    int paraCount = sectionElem.getElementCount();

    for (int i=0; i<paraCount; i++) {
        Element paraElem = sectionElem.getElement(i);
        AttributeSet attr = paraElem.getAttributes();

        // Get the name of the style applied to this paragraph element; may be null
        String sn = (String)attr.getAttribute(StyleConstants.NameAttribute);

        // Check if style name match
        if (style.getName().equals(sn)) {
            // Reapply the paragraph style
            int rangeStart = paraElem.getStartOffset();
            int rangeEnd = paraElem.getEndOffset();
            c.getStyledDocument().setParagraphAttributes(
                rangeStart, rangeEnd-rangeStart, style, true);
        }

        // Enumerate the content elements
        for (int j=0; j<paraElem.getElementCount(); j++) {
            Element contentElem = paraElem.getElement(j);
            attr = contentElem.getAttributes();

            // Get the name of the style applied to this content element; may be null
            sn = (String)attr.getAttribute(StyleConstants.NameAttribute);

            // Check if style name match
            if (style.getName().equals(sn)) {
                // Reapply the content style
                int rangeStart = contentElem.getStartOffset();
                int rangeEnd = contentElem.getEndOffset();
                c.getStyledDocument().setCharacterAttributes(
                    rangeStart, rangeEnd-rangeStart, style, true);
            }
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.