Reputation: 119
what I tried to do is if when I call the function then the line disappeared where caret is located in JTextArea. I achieved at first line case but hard to do in middle and last line cases.
This is perfectly failed code what I did.
private void DeleteOptionActionPerformed(ActionEvent e) {
String[] lines = area.getText().split("\n");
int caret = area.getCaretPosition();
int beforeLocation = 0;
for(int i = 0; i < area.getLineCount(); i++) {
try {
if(i == 0) {
if(caret <= lines[i].length())
area.replaceRange(null, area.getLineStartOffset(i), area.getLineEndOffset(i));
}
else {
if(caret <= lines[i].length() && caret > lines[beforeLocation].length()) {
area.replaceRange(null, area.getLineStartOffset(i), area.getLineEndOffset(i));
}
else {
caret -= lines[i].length();
beforeLocation = i;
continue;
}
}
} catch(BadLocationException e1) {
e1.printStackTrace();
}
caret -= lines[i].length();
beforeLocation = i;
}
}
Upvotes: 2
Views: 138
Reputation: 324118
Try using the Utilities
class.
No need for any looping logic. Code should be something like:
int offset = textArea.getCaretPosition();
int start = Utilities.getRowStart(...);
int end = Utilities.getRowEnd(...);
textArea.replaceRange("", start, end);
Upvotes: 3