Java Swing How to - Pad text in JTextPane








Question

We would like to know how to pad text in JTextPane.

Answer

import java.awt.Dimension;
import java.awt.FontMetrics;
//from  w w  w  .j  av  a  2s .  c o  m
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.TabSet;
import javax.swing.text.TabStop;

public class Main {
  public static void setTabs(JTextPane textPane, int charactersPerTab) {
    FontMetrics fm = textPane.getFontMetrics(textPane.getFont());
    int charWidth = fm.charWidth('w');
    int tabWidth = charWidth * charactersPerTab;

    TabStop[] tabs = new TabStop[5];

    for (int i = 0; i < tabs.length; i++) {
      int tab = i + 1;
      tabs[i] = new TabStop(tab * tabWidth);
    }

    TabSet tabSet = new TabSet(tabs);
    SimpleAttributeSet attributes = new SimpleAttributeSet();
    StyleConstants.setTabSet(attributes, tabSet);
    int length = textPane.getDocument().getLength();
    textPane.getStyledDocument().setParagraphAttributes(0, length, attributes,
        false);
  }

  public static void main(String[] args) {
    JTextPane textPane = new JTextPane();
    textPane.setText("12345678\n\t1\t2\t3a");
    JScrollPane scrollPane = new JScrollPane(textPane);
    scrollPane.setPreferredSize(new Dimension(700, 100));

    setTabs(textPane, 8);

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(scrollPane);
    frame.pack();
    frame.setVisible(true);
  }
}