If you want your new line to have the same indentation as the previous one, you can do that by simply checking the first characters of the previous line. Look at that :
public class Test {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame mainFrame = new JFrame("test");
mainFrame.setSize(300, 100);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = mainFrame.getContentPane();
pane.setLayout(new BorderLayout());
JTextPane jtp = new JTP();
pane.add(jtp);
mainFrame.setVisible(true);
}
});
}
static class JTP extends JTextPane {
JTP() {
((AbstractDocument)getDocument()).setDocumentFilter(new Filter());
}
}
static class Filter extends DocumentFilter {
@Override
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
StringBuilder indentatedString = new StringBuilder(string);
if(string.equals("\n")) {
AbstractDocument doc = ((AbstractDocument)fb.getDocument());
Element line = doc.getParagraphElement(offset);
int lineStart = line.getStartOffset(), lineEnd = line.getEndOffset();
String content = doc.getText(lineStart, lineEnd - lineStart);
int start = 0;
while(content.charAt(start)==' ') {
indentatedString.insert(0," ");
start++;
}
}
fb.insertString(offset, indentatedString.toString(), attr);
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text,
AttributeSet attrs) throws BadLocationException {
if(text.==0) {insertString(fb, offset, text, attrs);}
else if(text.length()>0) {remove(fb, offset, length);insertString(fb, offset, text, attrs);}
else {fb.replace(offset, length, text, attrs);}
}
}
}
The important part here is only the DocumentFilter that does the job.