Java JTextComponent Insert insertLineAfter(JTextComponent textComponent)

Here you can find the source of insertLineAfter(JTextComponent textComponent)

Description

insert Line After

License

Open Source License

Declaration

public static void insertLineAfter(JTextComponent textComponent) 

Method Source Code

//package com.java2s;
/*//from   w ww.j  a  va  2s.  c om
 * TextUtilities.java
 *
 * Copyright (C) 2002-2015 Takis Diakoumis
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 3
 * of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 */

import javax.swing.text.JTextComponent;

public class Main {
    public static void insertLineAfter(JTextComponent textComponent) {
        String newLine = "\n";
        int caretIndex = textComponent.getCaretPosition();

        StringBuilder sb = new StringBuilder(textComponent.getText());

        int endOfLineIndex = sb.indexOf(newLine, caretIndex);

        int length = sb.length();

        if (caretIndex == length || endOfLineIndex == length)
            sb.append(newLine);
        else
            sb.insert(endOfLineIndex == -1 ? 0 : endOfLineIndex, newLine);

        textComponent.setText(sb.toString());
        textComponent.setCaretPosition(endOfLineIndex == -1 ? length : endOfLineIndex + 1);
        sb = null;
    }
}

Related

  1. insert(final JTextComponent component, final String string)
  2. insertLineBefore(JTextComponent textComponent)
  3. insertMagicString(JTextComponent target, int dot, String toInsert)
  4. insertSimpleTemplate(JTextComponent target, String template)
  5. insertText(JTextComponent comp, String s)