Java Swing How to - Insert tab in JTextPane after linebreak








Question

We would like to know how to insert tab in JTextPane after linebreak.

Answer

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
import javax.swing.text.Element;
/*from w  w w.j  ava  2  s  .co  m*/
public class Main {
  public static void main(String[] args) {
    JTextArea textArea = new JTextArea(10, 30);
    AbstractDocument doc = (AbstractDocument) textArea.getDocument();
    doc.setDocumentFilter(new EndOfLineFilter());

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

class EndOfLineFilter extends DocumentFilter {
  @Override
  public void replace(FilterBypass fb, final int offset, int length,
      String text, AttributeSet a) throws BadLocationException {
    if (text.equals("\n")){
      text = addWhiteSpace(fb, offset, text);
    }
    super.replace(fb, offset, length, text, a);
  }

  private String addWhiteSpace(FilterBypass fb, int offset, String text)
      throws BadLocationException {
    Document doc = fb.getDocument();
    Element root = doc.getDefaultRootElement();
    int line = root.getElementIndex(offset);
    int i = root.getElement(line).getStartOffset();
    StringBuilder whiteSpace = new StringBuilder(text);

    while (true) {
      String temp = doc.getText(i, 1);
      if (temp.equals(" ") || temp.equals("\t")) {
        System.out.println("added");
        whiteSpace.append(temp);
        i++;
      } else{
        break;
      }        
    }
    return whiteSpace.toString();
  }
}