Java Swing How to - Print exception in JTextPane








Question

We would like to know how to print exception in JTextPane.

Answer

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.StyledDocument;
//  w ww .  ja  va  2 s.c o  m
public class Main extends JFrame {
  public static void main(String[] args) {
    new Main().setVisible(true);
  }
  private JTextPane text = new JTextPane();

  public Main() {
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    setSize(400, 300);

    Exception ex = new Exception();

    AttributeSet attr = null;
    StyledDocument doc = text.getStyledDocument();

    for (StackTraceElement trace : ex.getStackTrace()) {
      try {
        doc.insertString(doc.getLength(), trace.toString() + '\n', attr);
      } catch (BadLocationException ex1) {
        ex1.printStackTrace();
      }
    }
    getContentPane().add(new JScrollPane(text));
  }
}