Updated July 7, 2023
Introduction to JTextPane
JTextPane is used for stylizing a document and for representing it graphically and has embedded images and other components. It is a subclass of JEditorPane which forms the base for styled-components for the text provided by Java Swing Package. This can be also used for adding custom text formats and for unstyled text, an ordinary text area is used. JTextPane makes the use of styled documents using a StyledDocument interface as its model. Document interface is the parent from which the StyledDocument interface is derived. The document interface is also the default model for JTextPane.
Constructors of JTextPane
- public JTextPane(): This constructor displays a new blank text area. This creates a new instance of StyledEditorKit and sets the document model to null. This constructor is inherited from parent interface JEditorPane.
- public JtextPane(StyledDocument doc): A new JTextPane is created with the document model specified by the keyword doc here. This constructor is inherited from the parent interface Document.
Methods of JTextPane
There are fixed but innumerable methods implemented in JTextPane. A few of the major methods are listed down below:
1. Style
This method can be used to incorporate new styles into the logical style hierarchy. Following are a few of the child methods derived from Style are:
addStyle: This is used to add a new style to the hierarchy. The attributes are mentioned here are resolved in a bottom-up method such that the attribute given to the child will automatically override the same attribute from the parent.
Syntax:
public Style addStyle (String str, Style par)
str parameter is the name of the unique style within its collection. The name becomes null when the style goes unnamed. par is the parent style specified. This method addStyle returns the new Style.
removeStyle: This is used to remove a style which is a not-null one previously added to the document.
Syntax:
public void removedStyle(String str)
str being the name of the style to be removed
getStyle: It is used to fetch the name of the style not-null and which was previously added.
Syntax:
public Style getStyle (String str)
str is the name of the style to be retrieved
setLogicalStyle: Used to set the style to use the paragraph from the present caret position.
Syntax:
public void setLogicalStyle (Style log)
log being the logical style which is given to the paragraph
getLogicalStyle: Used to retrieve the logical style given to the paragraph set at the present caret position and returns the Style.
Syntax:
public Style getLogicalStyle()
2. AttributeSet()
There are a lot of subclasses that are used to retrieve the character attribute which is at the present position of caret. They are as follows:
- public AtrributeSet() getCharacterAttributes(): returns the attributes from the current caret position.
- public AttributeSet getParagraphAttributes(): Used to retrieve present paragraph attributes from current caret position.
- public AttributeSet setParagraphAttributes(Attribute atr, boolean new): Used to apply the attributes passed as parameters to the paragraph. In the case of selections, it applies the attributes to the paragraphs that intersect this selection. And in the case when there is no selection it is applied to the paragraph present at the current caret position. atr is the attribute passed and if the new parameter is given true, it first replaces the already existing attributes.
- public MutableAttributeSet getInputAttributes(): Used to fetch the input attributes for the pane.
- public void setCharacterAttributes(AttributeSet atr, boolean new): Used to apply the passed attributes to the character content. The attributes are applied to the selected range when a selection is present and if the selection is not present then the attributes are applied to any new text which is inserted. new if true returns the existing attributes
- public AttributeSet getCharacterAttributes(): Retrieves the character attributes present at the current caret location or null.
3. StyledDocument()
It is used to retrieve the model which is associated with the editor.
Syntax:
public StyledDocument getStyledDocument()
4. setDocument
Used to associate the editor with a text document which should belong to StyledDocument. It overrides the setDocument class from JTextComponent. Hence it is required that the document to be edited should be able to be converted to a StyledDocument without which it throws an IllegalArgumentException.
Syntax:
public void setDocument(Document new)
– new is the document to be displayed or changed.
5. setEditorKit
Used to set the kit which is presently installed for handling the content. This is the property that is used to establish the content type of the editor. It overrides the setEditorKit from the class JEditorPane. This also throws an IllegalArgumentException if the kit does not belong to StyledEditorKit.
Syntax:
public final void setEditorKit (EditorKit edit)
– the edit is the required kit behavior.
6. paramString
This returns a string representation of JTextPane.
Syntax:
protected String paramString()
– This method is used mostly for debugging and its content returned varies between different implementations. The returned string can be empty and not null.
Program to Implement JTextPane
Code:
//Importing all the dependancies of Java awt used for GUI purpose
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
//Importing all the dependancies of Java swing package also used for GUI purpose and has many built-in functions
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 JTextPaneTest {
//Handling BadLocationException to report such bad locations in the document model
public static void main(String args[]) throws BadLocationException {
//The string name we give here is displayed as the document name
JFrame jfr = new JFrame("Example of JTextPane");
// Makes the application to exit preventing it from running in the background
jfr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con = jfr.getContentPane();
JTextPane jpan = new JTextPane();
SimpleAttributeSet attrSet = new SimpleAttributeSet();
StyleConstants.setBold(attrSet, true);
// Attributes are set just before adding the text
jpan.setCharacterAttributes(attrSet, true);
jpan.setText("This ");
// Few of the other examples of attributes and features present in JTextPane
attrSet = new SimpleAttributeSet();
StyleConstants.setAlignment(attrSet, 1);
// Required colors can be set from the range of fixed available choices
StyleConstants.setForeground(attrSet, Color.yellow);
StyleConstants.setBackground(attrSet, Color.magenta);
Document doc = jpan.getStyledDocument();
doc.insertString(doc.getLength(), "is an ", attrSet);
attrSet = new SimpleAttributeSet();
StyleConstants.setItalic(attrSet, true);
StyleConstants.setForeground(attrSet, Color.RED);
StyleConstants.setBackground(attrSet, Color.cyan);
doc.insertString(doc.getLength(), "Example ", attrSet);
StyleConstants.setUnderline(attrSet, true);
StyleConstants.setFontSize(attrSet, 20);
doc.insertString(doc.getLength(), "of JTextPane ", attrSet);
// Scroll Pane is used to display a component and to change its size dynamically
JScrollPane scrollPane = new JScrollPane(jpan);
con.add(scrollPane, BorderLayout.CENTER);
jfr.setSize(550, 300);
jfr.setVisible(true);
}
}
Output:
Conclusion
Hence the JTextPane is always used in cases where the documents need to be graphically represented. All the attributes of a paragraph having a logical style attached have default values that will be applied in case they are not overridden. The advantage JTextPane has over Editor Panes is that it has these numerous built-in methods which are easy to call and work with. There is no need for any HTML or RTF file to embed images because of the provision of API’s given in the JTextPane class.
Recommended Articles
This is a guide to JTextPane. Here we discuss the methods, constructors, and program to implement JTextPane along with the syntax and output. You may also look at the following article to learn more –