Number of spaces before text in line in JTextPane

I would like to know how to count the number of spaces on a given line before the start of the actual text. Ex. if i have this in my JTextPane:

public static void main(String[] args) {
    int x = 1;



after typing 'x = 1;' and press enter, I would like to have the caret with the same indentation as 'int x = 1;' launches, so I don't have to constantly press the tab or manually enter spaces. Any suggestions?


source to share

3 answers

If you want your new line to have the same indentation as the previous one, you can do so by simply checking the first characters of the previous line. Look at this:

public class Test {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame mainFrame = new JFrame("test");
                mainFrame.setSize(300, 100);

                Container pane = mainFrame.getContentPane();
                pane.setLayout(new BorderLayout());

                JTextPane jtp = new JTP();


    static class JTP extends JTextPane {
        JTP() {
            ((AbstractDocument)getDocument()).setDocumentFilter(new Filter());

    static class Filter extends DocumentFilter {
        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," ");
            fb.insertString(offset, indentatedString.toString(), attr);
        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 just the DocumentFilter that does the job.



Check this first: Read the JTextPane line by line

Then you can just get the string and count the number of spaces .

int spaces = s.length() - s.replaceAll("^\\s+", "").length();



Split the JTextPane text by '\n'

and search each line until you find the String

one you are looking for.

If the line you are on does not have the String

one you are looking for, then you add the length of that line + 1 (to include '\n'

) to the amount.

If the line you are on has String

, then starting from the beginning of the line, count the number of spaces until you reach the 1st non-space character and add that number to the sum.

With the amount, you just provide it JTextPane.setCaretPosition()

. Something like:

int caretPosition = 0;
String[] lines = jTextPane1.getText().split("\n");
for (String line : lines) {
    if (line.contains(search)) {
        for (int i = 0; i < line.length(); i++) {
            if (line.charAt(i) != ' ') {
    } else {
        // +1 to include the '\n' character
        caretPosition += line.length() + 1;





All Articles