Java Swing How to - Change font size for JTextPane








Question

We would like to know how to change font size for JTextPane.

Answer

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
//from  w  ww .  j a v  a  2 s. c  om
import javax.swing.JComboBox;
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.StyleContext;
import javax.swing.text.StyledDocument;

public class Main {
  public static void main(String[] args) throws Exception {
    int SIZE = 14;
    String FONT = "Dialog";

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTextPane tp = new JTextPane();
    tp.setFont(new Font(FONT, Font.PLAIN, SIZE));
    tp.setPreferredSize(new Dimension(400, 300));
    StyledDocument doc = tp.getStyledDocument();
    Style defaultStyle = StyleContext.getDefaultStyleContext().getStyle(
        StyleContext.DEFAULT_STYLE);
    Style boldStyle = doc.addStyle("bold", defaultStyle);
    StyleConstants.setBold(boldStyle, true);
    String boldText = "this is bold test";
    String plainText = "this is plain.";

    doc.insertString(doc.getLength(), boldText, boldStyle);
    doc.insertString(doc.getLength(), plainText, defaultStyle);

    JPanel panel = new JPanel();
    panel.add(tp);

    JComboBox<String> zoomCombo = new JComboBox<String>(new String[] { "0.75", "1.00", "1.50",
        "1.75", "2.00" });
    zoomCombo.addActionListener(e ->{
        String s = (String) zoomCombo.getSelectedItem();
        double scale = new Double(s).doubleValue();
        int size = (int) (SIZE * scale);
        tp.setFont(new Font(FONT, Font.PLAIN, size));
      }
    );
    zoomCombo.setSelectedItem("1.00");
    JPanel optionsPanel = new JPanel();
    optionsPanel.add(zoomCombo);
    panel.setBackground(Color.WHITE);
    frame.add(panel, BorderLayout.CENTER);
    frame.add(optionsPanel, BorderLayout.NORTH);
    frame.pack();
    frame.setVisible(true);
  }
}