1. About JTextPane
The JTextPane component of Java Swing can render document like rich text content. So instead of a plain text, one can display styled text along with images. The JTextPane also supports housing the components like text field, combo boxes, etc. The styled text can have bold, italic, color, Font etc attributes applied to it. In this example, we will create a styled document using the JTextPane and StyleConstants.
2. StyleConstants & SimpleAttributeSet
In Swing, the text package holds both StyleConstants and SimpleAttributeSet. StyleConstants defines a set of styles and methods which plug those styles to the SimpleAttributeSet. For Example, the StyleConstants maintains a FontSize constant and provides a method to add that style constant to the SimpleAttributeSet by taking a number as a param.
Have a look at the below depiction:
JTextPane support two crucial functions. The insertIcon function can insert an image into the component and it needs an ImageIcon instance. We can construct this instance from the image file stored on the disc or internet.
The insertString method can insert a formatted string to the JTextPane. This method can take SimpleAttributeSet which holds a group of constants to apply text formatting. When we move to code, you will see how we use the StyleConstants to push the text styles to the Java Swing’s SimpleAttributeSet.
Know about JTextPane, StyleConstants and SimpleAttributeSet
3. About JTextPane Example
The below picture shows the example we create here:

The example is a JFrame Window which houses a JTextPane. Here, one can see the JTextPane Example displaying the content with a mixture of texts and images. The document displays heading text in blue colour and normal text in red colour. The heading text is slightly bigger than the normal text. Towards the end of the document, there will be document footer in green colour. This is not shown above.
Using this example, we will learn how to insert text and image into the JTextPane. At this moment, we can also visualize that we have three variations of the text and, in this example, we will group three types of text formatting styles to prepare the document.
4. Class Data Members
In the below code, at code snippet 02, we will see the data members for this example. JTextPane is the swing component which displays the document content. We also declare three styles to display blue heading text, normal red text, and green footer text. SimpleAttributeSet class of Java Swing will hold these style groups. Code snippet 01, we used it many times in our example and hence no explanation required here.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class JTextPaneExample extends JFrame { //Sample 02: Class Member JTextPane jtp; SimpleAttributeSet BlueTitleText; SimpleAttributeSet RedDescText; SimpleAttributeSet GreenDocFooter; public JTextPaneExample(String title) throws HeadlessException { super(title); // Sample 01: Set Size and Position setBounds(100, 100, 550, 500); Container ControlHost = getContentPane(); ControlHost.setLayout(new FlowLayout()); |
5. Create Style Groups – SimpleAttributeSet
Next, we create three groups via SimpleAttributeSet to hold the text formatting. Later, we will use these styling while preparing the document of this example.
1 2 3 4 |
// Sample 03: Create Style Groups SimpleAttributeSet BlueTitleText = new SimpleAttributeSet(); SimpleAttributeSet RedDescText = new SimpleAttributeSet(); SimpleAttributeSet GreenDocFooter = new SimpleAttributeSet(); |
6. Group StyleConstants via SimpleAttributeSet
The
StyleConstants class provides utility functions to add text formatting to the
SimpleAttributeSet. Say, for example, have a look at the code snippet 4.4a. Here, we are grouping four text formatting under a single attribute set called BlueTitleText
. By looking at this code snippet, one can say the title text will be in 20-Points Verdana font with blue bold formatting. In the same way, we group two other style attributes in two separate formatting groups. Now, our attribute set is ready and we will focus on creating the
JTextPane.
1 2 3 4 5 6 7 8 9 10 11 12 |
// Sample 04: Add Style to Groups //4a: Title Text StyleConstants.setBold(BlueTitleText, true); StyleConstants.setFontSize(BlueTitleText, 20); StyleConstants.setFontFamily(BlueTitleText, "Verdana"); StyleConstants.setForeground(BlueTitleText, Color.BLUE); //4b: Normal Text StyleConstants.setForeground(RedDescText, Color.RED); //4c: Footer Text StyleConstants.setItalic(GreenDocFooter, true); StyleConstants.setFontSize(GreenDocFooter, 32); StyleConstants.setForeground(GreenDocFooter, Color.GREEN); |
7. Create Scrollable JTextPane
We create the
JTextPane just like how we created the JEditorPane in the previous example. Here, we give our JTextPane
to the JScrollPane
to avail the scrolling capability. We ask the JScrollPane to provide both horizontal and vertical scrolling support.
1 2 3 4 5 6 7 |
//Sample 05: Create JTextPanel with Scroll bars jtp = new JTextPane(); JScrollPane jsc = new JScrollPane(jtp); jsc.setPreferredSize(new Dimension(530, 450 )); jsc.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); jsc.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); ControlHost.add(jsc); |
8. Move Cursor to End of JTextPane
Our JTextPane is ready and formatting groups also ready for the document creation. The below method will move the insertion point towards the end of the document. Prior to adding JTextPane content using the insertIcon and insertString methods, we will call this custom method.
1 2 3 4 5 6 7 8 |
//Sample 06: Move Cursor to Document End private void setInsertiontoDocEnd() { Document doc = jtp.getDocument(); int CurrentDocLength = doc.getLength(); jtp.setSelectionStart(CurrentDocLength); jtp.setSelectionEnd(CurrentDocLength); } |
JTextPane’s
getDocument method gives us the Document
instance and from that we can get the length of the document. Note, when we add the document content, its length will increase. We use this document length to move the insertion point towards the end of the document by calling the method
setSelectionStart and
setSelectionEnd. In our code snippet, we pass the document length to both these methods.
9. Insert Icon to JTextPane
Next, we write a method to insert icon to the JTextPane. Our method takes an ImageIcon
instance and adds that to the JTextPane
by calling the insertIcon
method. You can also notice how we call the setInsertiontoDocEnd
to move the cursor to the document end before inserting the image.
1 2 3 4 5 6 |
//Sample 07: Insert Content to Cursor's Location private void insertDocContent(ImageIcon img) { setInsertiontoDocEnd(); jtp.insertIcon(img); } |
10. Insert Styled Text to JTextPane
The custom function insertDocContent
is overloaded below by having two arguments from our previous version (Last section) which takes only one argument. Here, we moved the insertion point to the end of the document by calling our custom function setInsertiontoDocEnd
. But we do not need this as the
insertString Function will take care of the insert location.
Our custom function takes text we want to insert and the style we want to apply while setting the string to the document content. The style is of type
SimpleAttributeSet, which we defined in section 6. While we call the
insertString function of the Document
, we pass this SimpleAttributeSet
as param to apply the text formatting for the text we are going to insert. Also note, the first parameter denotes the insertion point and here we pass the length of the document. This means we always insert the string towards the end of the document. But, you can use this insertString
function to insert the string content anywhere in the document.
1 2 3 4 5 6 7 8 9 10 11 |
//Sample 08: Insert Content to Cursor's Location private void insertDocContent(String text, SimpleAttributeSet TextStyle) { setInsertiontoDocEnd(); Document doc = jtp.getDocument(); try { doc.insertString(doc.getLength(), text, TextStyle); } catch (BadLocationException e) { e.printStackTrace(); } } |
11. JTextPane Styled Document Content
We have all set and now we will create the content for the document. You can pick the map from below and save it as PNG files (India.png, France.png). Or you can use your own images.


Now look at the code below. At line 2 and 8, we create titles for the document in a blue text by calling our custom function insertDocContent
. Note, the third param passed the style attribute grouped under BlueTileText
, which is a
SimpleAttributeSet (Refer section 6). In the same way, we insert the normal red coloured text. For example, line 3-6 inserts a normal text in red color.
At line 7 and 17, we pass ImageIcon
instance from C:\temp location. Make sure you have these PNG files in your C:\temp location or change the code to refer to the image files on your disc. Since we overloaded the function insertDocContent
, we used it to insert both image and text contents. The key functions are insertIcon & insertString from Document, which will allow as to create the JTextPane document content dynamically.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
//Sample 09: Now let us create the Document insertDocContent("1.India\n", BlueTitleText); insertDocContent("India, officially the Republic of India, is a country " + "in South Asia. It is the second-most populous country, the " + "seventh-largest country by land area, and the most populous " + "democracy in the world.\n", RedDescText); insertDocContent(new ImageIcon("C:/temp/india.png")); insertDocContent("\n\n2.France\n", BlueTitleText); insertDocContent("France, in Western Europe, encompasses medieval " + "cities, alpine villages and Mediterranean beaches. Paris, " + "its capital, is famed for its fashion houses, classical " + "art museums including the Louvre and monuments like the " + "Eiffel Tower. The country is also renowned for its wines " + "and sophisticated cuisine. Lascaux’s ancient cave " + "drawings, Lyon’s Roman theater and the vast Palace of " + "Versailles attest to its rich history.\n", RedDescText); insertDocContent(new ImageIcon("C:/temp/france.png")); insertDocContent("\n\n\n\n This is a test document footer with " + "green italic style", GreenDocFooter); //Sample 09: Now let us create the Document insertDocContent("1.India\n", BlueTitleText); insertDocContent("India, officially the Republic of India, is a country " + "in South Asia. It is the second-most populous country, the " + "seventh-largest country by land area, and the most populous " + "democracy in the world.\n", RedDescText); insertDocContent(new ImageIcon("C:/temp/india.png")); insertDocContent("\n\n2.France\n", BlueTitleText); insertDocContent("France, in Western Europe, encompasses medieval " + "cities, alpine villages and Mediterranean beaches. Paris, " + "its capital, is famed for its fashion houses, classical " + "art museums including the Louvre and monuments like the " + "Eiffel Tower. The country is also renowned for its wines " + "and sophisticated cuisine. Lascaux’s ancient cave " + "drawings, Lyon’s Roman theater and the vast Palace of " + "Versailles attest to its rich history.\n", RedDescText); insertDocContent(new ImageIcon("C:/temp/france.png")); insertDocContent("\n\n\n\n This is a test document footer with " + "green italic style", GreenDocFooter); |
12. Watch Implementation as Youtube
13. Code Reference
13.1 MainEntry.java
1 2 3 4 5 6 7 8 9 |
package tube.coding.examples; public class MainEntry { public static void main(String[] args) { //Sample 07: Create Instance of JFrameDemo JTextPaneExample frame = new JTextPaneExample("JTextPane and Rich Text Content"); frame.setVisible(true); } } |
13.2 JavaSwingRadioButtonDemo.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
package tube.coding.examples; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.HeadlessException; import java.net.URL; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextPane; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; public class JTextPaneExample extends JFrame { //Sample 02: Class Member JTextPane jtp; SimpleAttributeSet BlueTitleText; SimpleAttributeSet RedDescText; SimpleAttributeSet GreenDocFooter; public JTextPaneExample(String title) throws HeadlessException { super(title); // Sample 01: Set Size and Position setBounds(100, 100, 550, 500); Container ControlHost = getContentPane(); ControlHost.setLayout(new FlowLayout()); // Sample 03: Create Style Groups SimpleAttributeSet BlueTitleText = new SimpleAttributeSet(); SimpleAttributeSet RedDescText = new SimpleAttributeSet(); SimpleAttributeSet GreenDocFooter = new SimpleAttributeSet(); // Sample 04: Add Style to Groups //4a: Title Text StyleConstants.setBold(BlueTitleText, true); StyleConstants.setFontSize(BlueTitleText, 20); StyleConstants.setFontFamily(BlueTitleText, "Verdana"); StyleConstants.setForeground(BlueTitleText, Color.BLUE); //4b: Normal Text StyleConstants.setForeground(RedDescText, Color.RED); //4c: Footer Text StyleConstants.setItalic(GreenDocFooter, true); StyleConstants.setFontSize(GreenDocFooter, 32); StyleConstants.setForeground(GreenDocFooter, Color.GREEN); //Sample 05: Create JTextPanel with Scroll bars jtp = new JTextPane(); JScrollPane jsc = new JScrollPane(jtp); jsc.setPreferredSize(new Dimension(530, 450 )); jsc.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); jsc.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); ControlHost.add(jsc); //Sample 09: Now let us create the Document insertDocContent("1.India\n", BlueTitleText); insertDocContent("India, officially the Republic of India, is a country " + "in South Asia. It is the second-most populous country, the " + "seventh-largest country by land area, and the most populous " + "democracy in the world.\n", RedDescText); insertDocContent(new ImageIcon("C:/temp/india.png")); insertDocContent("\n\n2.France\n", BlueTitleText); insertDocContent("France, in Western Europe, encompasses medieval " + "cities, alpine villages and Mediterranean beaches. Paris, " + "its capital, is famed for its fashion houses, classical " + "art museums including the Louvre and monuments like the " + "Eiffel Tower. The country is also renowned for its wines " + "and sophisticated cuisine. Lascaux’s ancient cave " + "drawings, Lyon’s Roman theater and the vast Palace of " + "Versailles attest to its rich history.\n", RedDescText); insertDocContent(new ImageIcon("C:/temp/france.png")); insertDocContent("\n\n\n\n This is a test document footer with " + "green italic style", GreenDocFooter); } //Sample 06: Move Cursor to Document End private void setInsertiontoDocEnd() { Document doc = jtp.getDocument(); int CurrentDocLength = doc.getLength(); jtp.setSelectionStart(CurrentDocLength); jtp.setSelectionEnd(CurrentDocLength); } //Sample 07: Insert Content to Cursor's Location private void insertDocContent(ImageIcon img) { setInsertiontoDocEnd(); jtp.insertIcon(img); } //Sample 08: Insert Content to Cursor's Location private void insertDocContent(String text, SimpleAttributeSet TextStyle) { setInsertiontoDocEnd(); Document doc = jtp.getDocument(); try { doc.insertString(doc.getLength(), text, TextStyle); } catch (BadLocationException e) { e.printStackTrace(); } } } |
Categories: Swing
Tags: insertIcon, insertString, setSelectionEnd, setSelectionStart, SimpleAttributeSet, StyleConstants