Search code examples
javaswingjtextfield

Remove lines in JTextArea


I'm trying to remove all the even lines in a JTextArea, but I'm having trouble getting that to work. My JTextArea is called "input" and I'm using a for loop to iterate through the lines and then remove all the even ones. My for loop:

for (int i=0; i<lineMax; i++) {
    if (lineNum % 2 == 0) {
        end = input.getLineEndOffset(0);
        input.replaceRange("", 0, end);
    }
    lineNum++;
}

If I put "This is a test" into my JTextArea with each word on a new line the output will be "a test" (with each word on a new line).


Solution

  • end = input.getLineEndOffset(0);
    input.replaceRange("", 0, end);
    

    That will always get the offset of the first line, so you will always be removing text from offset 0, to the end of the first line.

    The algorithm will be more complicated than that when you attempt to loop forward in the text area because every time you remove a line the offsets of the following lines change and the relative lines number change so you don't know which line is odd/even any more.

    An easier approach would be to start with the last line in the text area. This way relative line numbers of the previous lines will not change as you delete the text.

    You can use the following methods of the JTextArea to help with the logic:

    1. getLineCount() - start here and count back to line zero
    2. getLineEndOffset() and getLineStartOffset() - when you find an even line you get the two offsets and remove the text.