Java Swing How to - Use JTextPane to style code








Question

We would like to know how to use JTextPane to style code.

Answer

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
//from   w w w . j a v a  2  s.  c  o m
public class Main {
  public static void main(String args[]) {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTextPane ta = new JTextPane();
    ta.setContentType("text/html");
    ta.setText("<HTML><BODY><CODE> import java.io.*; <br> public class MyIO{}</CODE><br></BODY></HTML>");
    JScrollPane jsp = new JScrollPane(ta);
    f.getContentPane().add(jsp);

    f.setSize(300, 200);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
  }
}