Java Swing How to - Dynamically add styled text to JTextPane








Question

We would like to know how to dynamically add styled text to JTextPane.

Answer

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
/*  w  w w  . j a  va  2s. co  m*/
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

public class Main {
  public static void main(String[] args) {
    Fonts fs = new Fonts();
  }
}

class Fonts implements Runnable {
  String[] fnt;
  JTextPane jta = new JTextPane();

  GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
  StyledDocument doc;
  MutableAttributeSet mas;
  int cp = 0;
  int length = 0;

  public Fonts() {
    doc = jta.getStyledDocument();
    JScrollPane jsp = new JScrollPane(jta);
    jsp.setPreferredSize(new Dimension(400, 400));
    JFrame frm = new JFrame();
    frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frm.setLayout(new BorderLayout());
    frm.add(jsp, BorderLayout.CENTER);
    frm.setLocation(100, 100);
    frm.pack();
    frm.setVisible(true);
    jta.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    fnt = ge.getAvailableFontFamilyNames();
    mas = jta.getInputAttributes();
    new Thread(this).start();
  }

  @Override
  public void run() {
    for (int i = 0; i < fnt.length; i++) {
      StyleConstants.setBold(mas, false);
      StyleConstants.setItalic(mas, false);
      StyleConstants.setFontFamily(mas, fnt[i]);
      StyleConstants.setFontSize(mas, 16);
      dis(fnt[i]);
      try {
        Thread.sleep(75);
      } catch (Exception e) {
        e.printStackTrace();
      }
      StyleConstants.setBold(mas, true);
      dis(fnt[i] + " Bold");
      try {
        Thread.sleep(75);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    jta.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
  }

  Highlighter.HighlightPainter redPainter = new DefaultHighlighter.DefaultHighlightPainter(
      Color.red);

  public void dis(String s) {
    length = jta.getText().length();
    try {
      doc.insertString(cp, s, mas);
      doc.insertString(cp, "\n", mas);
    } catch (Exception bla_bla_bla_bla) {
      bla_bla_bla_bla.printStackTrace();
    }
    try {
      jta.getHighlighter().addHighlight(1, length - 1, redPainter);
    } catch (BadLocationException bla_bla_bla_bla) {
    }
  }
}