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?
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?
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.
Use
JTextComponent.setCaretPosition(int)
which: