Java Swing How to - Set JTextpane Tab Size








Question

We would like to know how to set JTextpane Tab Size.

Answer

//  w  ww . j  a v  a  2 s . com
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.TabSet;
import javax.swing.text.TabStop;

public class Main {
  public static void main(String[] args) {
    JTextPane pane = new JTextPane();
    TabStop[] tabs = new TabStop[2];
    tabs[0] = new TabStop(60, TabStop.ALIGN_RIGHT, TabStop.LEAD_NONE);
    tabs[1] = new TabStop(100, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE);
    TabSet tabset = new TabSet(tabs);

    StyleContext sc = StyleContext.getDefaultStyleContext();
    AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY,
        StyleConstants.TabSet, tabset);
    pane.setParagraphAttributes(aset, false);
    pane.setText("\tright\tleft\tcenter\tValue\n" 
        + "\t200.002\t200.002\t200.002\t200.002\n");

    JFrame d = new JFrame();    
    d.setContentPane(new JScrollPane(pane));
    d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    d.setSize(360, 120);
    d.setVisible(true);
  }
}