Java Swing How to - Make JTextPane adjust height to content








Question

We would like to know how to make JTextPane adjust height to content.

Answer

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//from   ww w.  ja  va2s  . c  om
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.text.Document;

public class Main extends JFrame {
  JTextField textField = new JTextField(20);
  JTextPane textPane;

  public Main() {
    textField.setText("Hit Enter to Add Text to Text Pane");
    getContentPane().add(textField, BorderLayout.NORTH);
    textField.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        try {
          Document doc = textPane.getDocument();
          doc.insertString(doc.getLength(), " " + textField.getText(), null);
          textField.setText("");//clear
          Dimension d = textPane.getPreferredSize();
          Rectangle r = textPane.modelToView(textPane.getDocument().getLength());
          d.height = r.y + r.height;
          textPane.setPreferredSize(d);
          getContentPane().validate();
        } catch (Exception e2) {
        }
      }
    });

    JPanel south = new JPanel();
    textPane = new JTextPane();
    textPane.setText("Some \ntext");
    textPane.setEditable(false);
    textPane.setPreferredSize(new Dimension(120, 23));

    south.add(textPane);
    getContentPane().add(south, BorderLayout.SOUTH);
  }

  public static void main(String[] args) {
    JFrame frame = new Main();
    frame.setSize(200, 200);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
    frame.setVisible(true);
  }
}