while true
while true

Reputation: 856

JTextArea - how to get first index of current line?

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

Answers (1)

Eng.Fouad
Eng.Fouad

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

Related Questions