假设我有一个 JTextArea
并且我想用特定文本替换当前行:
示例
123
123455
68967869
gh
现在我想替换当前光标现有行的文本。
所以如果光标在第三行,输出将是:
123
123455
replaced text
gh
现在我有了这段代码。但它只是附加到当前行而不是当前行的第一个位置。
jtextarea1.getDocument().insertString(jtextarea1.getCaretPosition(), "replaced text", null);
输出
123
123455
68967869replaced text//that's the problem
gh
最佳答案
使用JTextArea
API:
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);
关于java - JTextArea - 如何获取当前行的第一个索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26502421/