Reputation: 856
Suppose I have a JTextArea
and I want to replace current line with a specific text:
Example
123
123455
68967869
gh
Now I want to replace text of current cursor existing line.
So if cursor in the 3rd line, output will be:
123
123455
replaced text
gh
Now I have this code. But it just append to current line not to the fist position of current line.
jtextarea1.getDocument().insertString(jtextarea1.getCaretPosition(), "replaced text", null);
Output
123
123455
68967869replaced text//that's the problem
gh
Upvotes: 2
Views: 1650
Reputation: 117675
Use JTextArea
APIs:
JTextArea txt = ...;
int caretOffset = txt.getCaretPosition();
int lineNumber = txt.getLineOfOffset(caretOffset);
int startOffset = txt.getLineStartOffset(lineNumber);
int endOffset = txt.getLineEndOffset(lineNumber);
txt.replaceRange("Replaced Text", startOffset, endOffset);
Upvotes: 5