Java Swing How to - Get style from JTextPane and set to another JTextPane








Question

We would like to know how to get style from JTextPane and set to another JTextPane.

Answer

import java.awt.BorderLayout;
import java.awt.Color;
/*from  w w w  . ja va2s .  com*/
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Element;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import javax.swing.text.StyledEditorKit;

public class Main {
  static AttributeSet attribute;
  static Document doc1, doc2;

  private static void append1(String text) {
    try {
      doc1.insertString(doc1.getLength(), text, attribute);
    } catch (BadLocationException ex) {
      ex.printStackTrace();
    }
  }

  private static void append2(String text, AttributeSet attributeNew) {
    try {
      doc2.insertString(doc2.getLength(), text, attributeNew);
    } catch (BadLocationException ex) {
      ex.printStackTrace();
    }
  }

  public static void main(String args[]) throws BadLocationException {
    JTextPane textPane1 = new JTextPane();
    
    MutableAttributeSet black = new SimpleAttributeSet();
    MutableAttributeSet red = new SimpleAttributeSet();

    StyleConstants.setForeground(black, Color.black);
    StyleConstants.setForeground(red, Color.red);
    textPane1.setEditorKit(new StyledEditorKit());
    doc1 = textPane1.getDocument();

    append1("This is a Test!\n");

    attribute = red;
    append1("Hello world! Hello Stackoverflow\n");

    attribute = black;
    append1("the text is black again\n");

    StyledDocument styledDocument = textPane1.getStyledDocument();
    Element element;

    JTextPane textPane2 = new JTextPane();
    textPane2.setEditorKit(new StyledEditorKit());

    doc2 = textPane2.getDocument();
    for (int i = 0; i < styledDocument.getLength(); i++) {
      element = styledDocument.getCharacterElement(i);
      AttributeSet attributeNew = element.getAttributes();
      System.out.println(i);
      append2(styledDocument.getText(i, 1), attributeNew);
    }

    JFrame frame1 = new JFrame();
    frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame1.setSize(400, 300);
    frame1.getContentPane()
        .add(new JScrollPane(textPane1), BorderLayout.CENTER);
    frame1.setVisible(true);

    JFrame frame2 = new JFrame();
    frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame2.setSize(400, 300);
    frame2.setLocation(300, 0);
    frame2.getContentPane()
        .add(new JScrollPane(textPane2), BorderLayout.CENTER);
    frame2.setVisible(true);
  }
}