Friday, May 30, 2014

Setting text styles, colors, font and alignment in JTextPane (2): html

You can also setting the styles, colors, font and other character of the text in JTextPane using html. Following is an example code.

import java.awt.Color;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;

public class HtmlTest extends JTextPane {
 
    public static void main(String[] args){
        //create the JTextPane and set the ContentType to text/html
        HtmlTest test = new HtmlTest();
        test.setContentType("text/html");
        test.setBackground(Color.yellow);
     
        String str = "<p align='center'><font size='14' color='blue' style='background-color: gray;'>Style Test Result</font></p><br/>"+
                    "<font size='8' color='red' style='background-color:green;'>the first line</font><br/>"+
                    "the second line<br/>";
     
        //get the HTMLEditorKit
        HTMLDocument doc = (HTMLDocument)test.getDocument();
        HTMLEditorKit editorKit = (HTMLEditorKit)test.getEditorKit();
        try{
            //insert the text using the HTMLEditorKit
            editorKit.insertHTML(doc, doc.getLength(), str,0,0, null);
        }catch(BadLocationException ble){
            ble.printStackTrace(System.out);
        } catch(IOException ioe){
            ioe.printStackTrace(System.out);
        }
     
        JFrame f = new JFrame("Style Test");
        f.setContentPane(new JScrollPane(test));
        f.setSize(500, 300);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

           Previous <

References

1. Setting text styles, colors, font and alignment in JTextPane (1): attributes

-------------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

1 comment: