How to share style between JTextPanes?

How to share style between JTextPanes?

There are situations where we need to share the styles for fonts paragraphs for multiple JTextPanes. In this article we will see how we can achieve this.

By default JTextPane do not share the styles. But lets see how we can share the styles between JTextPane.
As we all know, Styles are stored in a style context and JTextPane have their style document i.e. DefaultStyledDocument.
By default, text panes do not have same style contexts, so any style created for a that particular text pane is available only in that text pane.
So for having two textpane sharing same style we need a style document having same style context. So as shown in in example below we will create two text panes that share a style context by DefaultStyledDocument with same style context. So the styles get shared between two textpane.

Example for sharing style between JTextPanes

Steps Done :
1. Create two JTextPane instances
2. Create StyleContext instance.
3. Create two DefaultStyledDocument instances and set it to the JTextPane using setDocument method.
4. Adding style to one of the JTextPane

Code snippet showing sharing of style between JTextPanes

public static void main(String[] argv) throws Exception {

JTextPane textPane1 = new JTextPane(); // Creating two different JTextPanes
JTextPane textPane2 = new JTextPane();

StyleContext styleContext = new StyleContext();

textPane1.setDocument(new DefaultStyledDocument(styleContext)); // Setting DefaultStyledDocument to each JTextPane
textPane2.setDocument(new DefaultStyledDocument(styleContext));

Style style = textPane1.addStyle("blue", null); //Creating and adding style to textPane1
StyleConstants.setBackground(style, Color.ORANGE);
String text = "This is an example of sharing a style between JTextPane";
style = textPane2.getStyle("blue");
StyleConstants.setForeground(style, Color.GREEN);
try {
textPane1.getStyledDocument().insertString(textPane1.getStyledDocument().getLength(), text, style);
} catch (BadLocationException badLocationException) {
System.err.println("Bad Location");
try {
textPane2.getStyledDocument().insertString(textPane2.getStyledDocument().getLength(), text, style);
} catch (BadLocationException badLocationException) {
System.err.println("Bad Location");
JFrame frame = new JFrame();
frame.setLayout(new java.awt.GridLayout(0, 1));
frame.add(new JLabel("Other one"));
frame.setSize(150, 150);


Thus we have seen how to share style between JTextPanes.
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


Post a Comment