Java Swing How to - Set margin for JTextPane








Question

We would like to know how to set margin for JTextPane.

Answer

import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Insets;
//ww w .  j  a va2  s.c om
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;

public class Main {
  public static void main(String[] args) {
    final JTextPane textPane = new JTextPane();
    final JScrollPane scrollPane = new JScrollPane(textPane);

    String text = "Lorem ipsum dolor sit amet, "
        + "consectetur adipiscing elit."
        + "Fusce nec sapien id diam consequat adipiscing.";
    textPane.setText(text);

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(scrollPane);

    frame.setSize(new Dimension(200, 200));
    frame.setVisible(true);

    FontMetrics metrics = textPane.getFontMetrics(textPane.getFont());
    textPane.setMargin(new Insets(scrollPane.getViewport().getHeight()
        - metrics.getHeight(), 0, 0, 0));
  }
}