Automatically Updating Styled Text When a Style Is Updated - Java Swing

Java examples for Swing:JTextPane

Description

Automatically Updating Styled Text When a Style Is Updated

Demo Code


import java.awt.Color;

import javax.swing.JTextPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.Element;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;

public class Main {
  public static void main(String[] args) {
    JTextPane textPane = new JTextPane();
    ChangeListener changeListener = new ChangeListener() {
      public void stateChanged(ChangeEvent e) {
        reapplyStyles(textPane, (Style) e.getSource());
      }/*from w  ww  .  j av a 2 s  . co m*/
    };

    // 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);
  }
  public static void reapplyStyles(JTextPane c, Style style) {
    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();

      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();

        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);
        }
      }
    }
  }
}

Related Tutorials