Java Swing How to - Implement your own style for JTextPane








Question

We would like to know how to implement your own style for JTextPane.

Answer

/* w  w  w  .j a  v a  2s . c om*/
import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    JTextPane textPane = new JTextPane();

    JButton button = new JButton("Test");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    panel.setLayout(new BorderLayout());
    panel.setPreferredSize(new Dimension(200, 200));

    panel.add(textPane, BorderLayout.CENTER);
    panel.add(button, BorderLayout.SOUTH);
    textPane.addStyle("myStyle", null);

    button.addActionListener(e ->{
      StyledDocument doc = textPane.getStyledDocument();
        int start = textPane.getSelectionStart();
        int end = textPane.getSelectionEnd();
        if (start == end) { 
          return;
        }
        if (start > end) { 
          int life = start;
          start = end;
          end = life;
        }
        Style style = textPane.getStyle("myStyle");

        if (StyleConstants.isBold(style)) {
          StyleConstants.setBold(style, false);
        } else {
          StyleConstants.setBold(style, true);
        }
        doc.setCharacterAttributes(start, end - start, style, false);
      }
    );

    frame.add(panel);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}