/**
* Delete the line where the cursor is positioned.
*/
public void deleteCurrentLine() {
// ab^EndPos: so EndPos is 3, there are 2 characters a, b, ^ is the flag
// of end of the document.
int length = getDocument().getLength();
if (length <= 0) { return; }
Element root = getDocument().getDefaultRootElement();
int pos = getCaretPosition();
int lineNumber = root.getElementIndex(pos); // 取得光標(biāo)所在行的行號(hào)
Element e = root.getElement(lineNumber);
int start = e.getStartOffset();
int end = e.getEndOffset(); // 取得所在行最后回車的下一個(gè)位置, 有可能是文檔結(jié)束位置
if (end == root.getEndOffset()) {
// 如果是文檔結(jié)束,則刪除前一行的回車,且跳到文檔結(jié)束的前一位置,其為行的有效位置
start = Math.max(0, start - 1); // 刪除前一行最后的回車
end--;
}
try {
getDocument().remove(start, end - start);
// 設(shè)置光標(biāo)在所在行的首行
lineNumber = root.getElementIndex(start);
e = root.getElement(lineNumber);
start = e.getStartOffset();
setCaretPosition(start);
} catch (BadLocationException e2) {
e2.printStackTrace();
}
/*
start = Math.max(0, start - 1); // 刪除前一行最后的回車
end = Math.min(end, root.getEndOffset() - 1); //
// 最后一行的時(shí)候,要往前跳一個(gè)位置跳過文檔結(jié)束符
// System.out.println("Start:" + start + ", End: " + end);
if (start == 0) {
getDocument().remove(start, end - start); // 第一行的時(shí)候,要把第一行尾的回車刪除
} else if (end + 1 == root.getEndOffset()) {
getDocument().remove(start, end - start);
// 最后一行時(shí),刪除后設(shè)置光標(biāo)到行的最前面
pos = root.getElement(root.getElementIndex(start)).getStartOffset();
setCaretPosition(pos);
} else {
getDocument().remove(start, end - start - 1); // 刪除前一行的回車,留這一行的回車
setCaretPosition(start + 1); // 設(shè)置光標(biāo)在下一行的首行
}*/
}