/**
* 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); // 取得光標所在行的行號
Element e = root.getElement(lineNumber);
int start = e.getStartOffset();
int end = e.getEndOffset(); // 取得所在行最后回車的下一個位置, 有可能是文檔結束位置
if (end == root.getEndOffset()) {
// 如果是文檔結束,則刪除前一行的回車,且跳到文檔結束的前一位置,其為行的有效位置
start = Math.max(0, start - 1); // 刪除前一行最后的回車
end--;
}
try {
getDocument().remove(start, end - start);
// 設置光標在所在行的首行
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); //
// 最后一行的時候,要往前跳一個位置跳過文檔結束符
// System.out.println("Start:" + start + ", End: " + end);
if (start == 0) {
getDocument().remove(start, end - start); // 第一行的時候,要把第一行尾的回車刪除
} else if (end + 1 == root.getEndOffset()) {
getDocument().remove(start, end - start);
// 最后一行時,刪除后設置光標到行的最前面
pos = root.getElement(root.getElementIndex(start)).getStartOffset();
setCaretPosition(pos);
} else {
getDocument().remove(start, end - start - 1); // 刪除前一行的回車,留這一行的回車
setCaretPosition(start + 1); // 設置光標在下一行的首行
}*/
}