How to re-position cursor in JTextArea

2.2k views Asked by At

I have set some text in JTextArea. The cursor is in the 5th line. Now I want to set some text in the first line.

So is it possible to re-position the cursor to the desired line?

2

There are 2 answers

0
Andrew Thompson On

Use JTextComponent.setCaretPosition(int) which:

Sets the position of the text insertion caret for the TextComponent. Note that the caret tracks change, so this may move if the underlying text of the component is changed. If the document is null, does nothing. The position must be between 0 and the length of the component's text or else an exception is thrown.

2
DevilsHnd - 退した On

If you want to go from one actual text line to another text line then you still need to use the JTextComponent.setCaretPosition() method but what you will also need is a means to get the desired line starting index to pass to the JTextComponent.setCaretPosition() method. Here is how you can get the starting index of any supplied line number providing the line number supplied exists within the document:

public int getLineStartIndex(JTextComponent textComp, int lineNumber) {
    if (lineNumber == 0) { return 0; }

    // Gets the current line number start index value for 
    // the supplied text line.
    try {
        JTextArea jta = (JTextArea) textComp;
        return jta.getLineStartOffset(lineNumber-1);
    } catch (BadLocationException ex) { return -1; }
}

How you might use the above method (let's say from the ActionPerformed event of a JButton):

int index = getLineStartIndex(jTextArea1, 3);
if (index != -1) { 
    jTextArea1.setCaretPosition(index);
}
jTextArea1.requestFocus();

The example usage code above will move the caret (from whatever location it happens to be in within the document) to the beginning of line 3 within the same document.

EDIT: Based on question in comments...

To move the caret to the end of a line you can make yet another method very similar to the getLineStartIndex() method above except now we'll name it getLineEndIndex() and we'll make a single code line change:

public int getLineEndIndex(JTextComponent textComp, int lineNumber) {
    if (lineNumber == 0) { return 0; }

    // Gets the current line number end index value for 
    // the supplied text line.
    try {
        JTextArea jta = (JTextArea) textComp;
        return jta.getLineEndOffset(lineNumber-1) - System.lineSeparator().length();
    } catch (BadLocationException ex) { return -1; }
}

Use this method the same way as the getLineStartIndex() method shown above.