Java Swing How to - Calculate lines with LineBreakMeasurer and change fontsize for JTextPane








Question

We would like to know how to calculate lines with LineBreakMeasurer and change fontsize for JTextPane.

Answer

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
/*ww  w. j  a v a2 s.co  m*/
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.border.LineBorder;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

public class Main {
    static JTextPane textPane = new JTextPane();
    static int size = 20;
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(new JButton(new AbstractAction("Update") {
            @Override
            public void actionPerformed(ActionEvent ae) {
                
                    StyledDocument doc = (StyledDocument) textPane.getDocument();
                    SimpleAttributeSet style = new SimpleAttributeSet();
                    StyleConstants.setFontFamily(style, "Serif");
                    StyleConstants.setFontSize(style, size++);
                    try {
                        doc.insertString(doc.getLength(), " one two three", style);
                        Dimension d = textPane.getPreferredSize();
                        Rectangle r = textPane.modelToView(textPane.getDocument().getLength());
                        d.height = r.y + r.height;
                        textPane.setPreferredSize(d);
                    } catch (BadLocationException e) {
                        e.printStackTrace();
                    }
                    frame.pack();
                }
           
        }));
        frame.add(buttonPanel, BorderLayout.NORTH);
            textPane.setText("this is a test.");
            textPane.setBorder(new LineBorder(Color.BLACK));
         
        frame.add(new JScrollPane(textPane));
        frame.pack();
        frame.setVisible(true);
    }
}