Search code examples
javaswingjtextcomponentstyleddocumentdefaultstyleddocument

Custom tabs in jtextarea in java


How to set tab stops in jtextarea for different lengths,

first tab should stop 4

Second tab should stop at 20 (If i give tab from 4 it should stop at 20)

Third tab should stop at 30 (If i give tab from 0 it should stop at 30)


Solution

  • Try something like this.

    StyledDocument document = new DefaultStyledDocument():
    
    SimpleAttributeSet attributes = new SimpleAttributeSet();
    
    TabStop[] tabStops = new TabStop[3];
    tabStops[0] = new TabStop(4.0, TabStop.ALIGN_LEFT, TabStop.LEAD_DOTS);
    tabStops[1] = new TabStop(20.0, TabStop.ALIGN_LEFT, TabStop.LEAD_DOTS);
    tabStops[2] = new TabStop(30.0, TabStop.ALIGN_LEFT, TabStop.LEAD_DOTS);
    
    TabSet tabSet = new TabSet(tabStops);
    StyleConstants.setTabSet(attributes, tabSet);
    document.setParagraphAttributes(0, 0, attributes, false);
    

    When you create the JTextArea, use the Document constructor.