I have an editor in which I want to check that selected text will not contain some words. If it contains those particular words, then I need to deselect the selection made by user. Is there any way to do that in JTextPane
?
Asked
Active
Viewed 4,505 times
3 Answers
7
I am not sure, but try this method.
textPane.setCaretPosition(start);

Andrew Thompson
- 168,117
- 40
- 217
- 433

bugs_
- 3,544
- 4
- 34
- 39
7
int end = pane.getSelectionEnd();
pane.setSelectionStart(end);
pane.setSelectionEnd(end);
This will deselect the selected text and leave the caret at the end of whatever the user selected. It might pay to pop a JOptionPane
telling the user why the selection disappeared..
JOptionPane.showMessageDialog(
null,
"Don't select swear words!",
"Net Nanny says..",
JOptionPane.ERROR_MESSAGE);

Andrew Thompson
- 168,117
- 40
- 217
- 433
2
Text selection is temporaray and contiguous. You can't unselect some text in the middle of a larger string of selected text.
Maybe you are talking about highlighting. Check out the API for getHighlighter(). You can add/remove highlights and specify the start/end offsets of each highlight.

camickr
- 321,443
- 19
- 166
- 288
-
or just jtextpane.setSelectionStart(0); and jtextpane.setSelectionEnd(0); and it will "clear" the selection. – george_h Dec 19 '13 at 14:10