Java Swing How to - Print content of JTextPane








Question

We would like to know how to print content of JTextPane.

Answer

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//from  w  w w  .j  a  v  a2  s .c o  m
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.text.html.HTMLEditorKit;

public class Main {
  public static void main(String[] args) {
    JFrame jframe = new JFrame();
    jframe.setSize(500, 200);
    jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTextPane jTextPane = new JTextPane();
    jTextPane.setEditorKit(new HTMLEditorKit());
    JButton btn = new JButton("Print");
    btn.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent arg0) {
        try {
          jTextPane.setContentType("text/html");
          boolean done = jTextPane.print();
          if (done) {
            System.out.println("Printing is done");
          } else {
            System.out.println("Error while printing");
          }
        } catch (Exception pex) {
          pex.printStackTrace();
        }
      }
    });
    jframe.add(btn, BorderLayout.SOUTH);
    jframe.add(jTextPane);
    jframe.setVisible(true);
  }
}