JTextPane Study 1

If you want to do very much with Java, you will soon find yourself trying to work with formatted text. Java has several ways to deal with different types of text, but one of the most powerful is JTextPane.

Being powerful has its downside. JTextPane isn’t as easy to use as many of the other classes and methods. What it does have is the power of an entire word processor under the hood, it that’s the amount of power you feel you need.

Below are just a few of the basic methods available to JTextPane that will let you create formatted text on the computer screen. This study doesn’t cover all the methods available for JTextPane. It doesn’t even cover a fraction of the available methods. What it does is give you a toehold into the methods and function of this incredibly powerful group of classes.

You can download the project to import into NetBeans here: JTextPaneStudy.zip

Below is all the code contained in the project. It contains one file consisting of two different classes. The inner class creates a simple JPanel with a few clickable controls. The outer class creates the JTextPane and puts it all together into a Jframe.

package GUI;

// imports
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
    // These imports are for the inner class
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.FlowLayout;
import java.awt.Font;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JPanel;
import javax.swing.JComboBox;
import javax.swing.JToggleButton;

public class MainJFrame extends JFrame {
    
    // final variables
    final int WIN_WIDTH = 600;
    final int WIN_HEIGHT = 400;
    final int MEDIUM = 16;
    final int LARGE = 20;
    final int SMALL = 12;

    // class variables
    int endDot;
    JScrollPane textPaneScrollPane;
    JTextPane jTextPane;
    StyledDocument styledDocument;
    SimpleAttributeSet simpleAttributeSet;
    AttributeSet tempTextAttributeSet, endAttributeSet;
    TextControls textControls;
    
    // constructor
    public MainJFrame() {
        createJTextPaneAndListeners();
        textPaneScrollPane = new JScrollPane(jTextPane);
        textControls = new TextControls();
        this.setLayout(new BorderLayout());
        this.setTitle("JTextPane Study");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.add(textControls, BorderLayout.NORTH);
        this.add(textPaneScrollPane, BorderLayout.CENTER);
    }
    
    // creating JTextPane and add text styles to it
    private void createJTextPaneAndListeners() {
        jTextPane = new JTextPane();
        styledDocument = jTextPane.getStyledDocument();
        jTextPane.setPreferredSize(new Dimension(WIN_WIDTH, WIN_HEIGHT));
        simpleAttributeSet = new SimpleAttributeSet();
        StyleConstants.setFontFamily(simpleAttributeSet, "SansSerif");
        StyleConstants.setFontSize(simpleAttributeSet, MEDIUM);
        endAttributeSet = simpleAttributeSet.copyAttributes();
        jTextPane.setCharacterAttributes(simpleAttributeSet, true);
        jTextPane.setParagraphAttributes(simpleAttributeSet, true);
        jTextPane.addCaretListener(new CaretListener() {
            @Override
            public void caretUpdate(CaretEvent event) {
                textPaneCaretListener(event);
            }
        });
    }
    
    public void textPaneCaretListener(CaretEvent event) {
        int currentDot;
        currentDot = event.getDot();
        endDot = styledDocument.getLength();
        if(currentDot != endDot) {
            tempTextAttributeSet = jTextPane.getCharacterAttributes();
            textControls.updateButtons(tempTextAttributeSet);
        } else {
            jTextPane.setCharacterAttributes(endAttributeSet, true);
            textControls.updateButtons(endAttributeSet);
        }
    }
    
    private static void createAndShowGUI() {
        MainJFrame mainJFrame = new MainJFrame();
        mainJFrame.pack();
        mainJFrame.setVisible(true);
    }
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                createAndShowGUI();
            }
        });
    }
    
    /*
    *
    *
    * Inner class created for a control surface
    *
    *
    */
    
    class TextControls extends JPanel {
    
        // Variables
        private JToggleButton boldButton;
        private JToggleButton italicButton;
        private JComboBox textSizeComboBox;
    
        // constructor
        public TextControls() {
            boldButton = new JToggleButton();
            italicButton = new JToggleButton();
            textSizeComboBox = new JComboBox();

            setLayout(new FlowLayout(FlowLayout.LEADING));

            boldButton.setFont(new Font("Tahoma", 1, 11)); // NOI18N
            boldButton.setText("Bold");
            add(boldButton);
            boldButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent event) {
                    boldButtonActionPerformed(event);
                }
            });

            italicButton.setFont(new Font("Tahoma", 2, 11)); // NOI18N
            italicButton.setText("Italic");
            add(italicButton);
            italicButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent event) {
                    italicButtonActionPerformed(event);
                }
            });

            textSizeComboBox.setModel(new DefaultComboBoxModel(
                    new String[] { "Small", "Medium", "Large" }));
            textSizeComboBox.setSelectedIndex(1);
            add(textSizeComboBox);
            textSizeComboBox.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent event) {
                    textSizeComboBoxActionPerformed(event);
                }
            });
        } // end of constructor
        
        public void updateButtons(AttributeSet set) {
            boldButton.setSelected(StyleConstants.isBold(set));
            italicButton.setSelected(StyleConstants.isItalic(set));
            int size = StyleConstants.getFontSize(set);
            switch(size) {
                case SMALL:
                    textSizeComboBox.setSelectedIndex(0);
                    break;
                case MEDIUM:
                    textSizeComboBox.setSelectedIndex(1);
                    break;
                case LARGE:
                    textSizeComboBox.setSelectedIndex(2);
                    break;
            }
        }
        
        public void boldButtonActionPerformed(ActionEvent event) {
            StyleConstants.setBold(simpleAttributeSet, boldButton.isSelected());
            endAttributeSet = simpleAttributeSet.copyAttributes();
            jTextPane.setCharacterAttributes(simpleAttributeSet, true);
            jTextPane.requestFocusInWindow();
        }
        
        public void italicButtonActionPerformed(ActionEvent event) {
            StyleConstants.setItalic(simpleAttributeSet, italicButton.isSelected());
            endAttributeSet = simpleAttributeSet.copyAttributes();
            jTextPane.setCharacterAttributes(simpleAttributeSet, true);
            jTextPane.requestFocusInWindow();
        }
        
        public void textSizeComboBoxActionPerformed(ActionEvent event) {
            int selected = textSizeComboBox.getSelectedIndex();
            switch(selected) {
                case 0:
                    StyleConstants.setFontSize(simpleAttributeSet, SMALL);
                    break;
                case 1:
                    StyleConstants.setFontSize(simpleAttributeSet, MEDIUM);
                    break;
                case 2:
                    StyleConstants.setFontSize(simpleAttributeSet, LARGE);
                    break;
                default:
                    StyleConstants.setFontSize(simpleAttributeSet, MEDIUM);
                    break;
            }
            endAttributeSet = simpleAttributeSet.copyAttributes();
            jTextPane.setCharacterAttributes(simpleAttributeSet, true);
            jTextPane.requestFocusInWindow();
        }
        
    } // End Inner Class TextControls
    
} // End Outer Class MainJFrame

Advertisements

Published by

Marisa

I am a writer of words, a thinker of thoughts, a changer of genders, and a queerer of life. I am an antagonist of the ordinary; and while I do tolerate it, I also look at it with contempt.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s