how to use CSS style or stylesheet in java swing JEditorPane ?

Use stylesheet in java swing JEditorPane

Are you looking for inserting css styles in your swing application, then no need to worry, because Java Swing provides option for inserting css information into the JEditorPane. It is similar to the adding html code in the JEditorPane. Now lets see step by step how to add css or stylesheet information into the JEditorPane.

1. Create a JEditorPane.
JEditorPane cssinEditorPane = new JEditorPane();


2. Next step is to add HTMLEditorKit to JEditorPane
HTMLEditorKit cssKit = new HTMLEditorKit();
cssinEditorPane.setEditorKit(cssKit);

3. Then need to get an instance of the StyleSheet class from your HTMLEditorKit and add various rules such as h1 and h2 using add rule method of stylesheet.

    StyleSheet styleSheet = cssKit.getStyleSheet();
    styleSheet.addRule("body {font-family:verdana; margin: 15px; }");
    styleSheet.addRule("h1 {color: #800000;}");
    styleSheet.addRule("h2 {color: #008000;}");


4. Now its time to look how we will see the html text in the JEditorPane but before that we need to do couple of steps such as
1. Need to get document from createDefaultDocument()
2. Set that document to the JEditorPane

    Document doc = cssKit.createDefaultDocument();
    cssinEditorPane.setDocument(doc);

5. Now we need to just add the text in JEditorPane:

cssinEditorPane.setText(cssText);

Now lets see how output looks like :

Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

2 comments:

  1. was really helpful..
    simple n easy way to understand..

    ReplyDelete
  2. Radhakanta Ghosh26 May 2015 at 11:36

    Good tutorial... Got some new concepts. Thanks

    ReplyDelete