?? e972. finding word boundaries in a jtextcomponent.txt
字號:
This example demonstrates an action that selects the word adjacent to the caret. If the caret is adjacent to two words, the word following the caret is selected. The implementation uses BreakIterator.getWordInstance() to find word boundaries.
public TextAction selectWordAction = new TextAction("Select Word") {
public void actionPerformed(ActionEvent evt) {
JTextComponent c = getTextComponent(evt);
if (c == null) {
return;
}
int pos = c.getCaretPosition();
try {
// Find start of word from caret
int start = Utilities.getWordStart(c, pos);
// Check if start precedes whitespace
if (start < c.getDocument().getLength()
&& Character.isWhitespace(c.getDocument().getText(start, 1).charAt(0))) {
// Check if caret is at end of word
if (pos > 0
&& !Character.isWhitespace(c.getDocument().getText(pos-1, 1).charAt(0))) {
// Start searching before the caret
start = Utilities.getWordStart(c, pos-1);
} else {
// Caret is not adjacent to a word
start = -1;
}
}
if (start != -1) {
// A non-whitespace character follows start.
// Find end of word from start.
int end = Utilities.getWordEnd(c, start);
// Set selection
c.setSelectionStart(start);
c.setSelectionEnd(end);
}
} catch (BadLocationException e) {
}
}
};
public TextAction selectNextWordAction = new TextAction("Select Next Word") {
public void actionPerformed(ActionEvent evt) {
JTextComponent c = getTextComponent(evt);
if (c == null) {
return;
}
int pos = c.getSelectionStart();
int len = c.getDocument().getLength();
try {
// Find start of next word from selection.
// getNextWord() throws BadLocationException if no word follows pos.
int start = Utilities.getNextWord(c, pos);
// Find end of word from start
int end = Utilities.getWordEnd(c, start);
// Set selection
c.setSelectionStart(start);
c.setSelectionEnd(end);
} catch (BadLocationException e) {
}
}
};
public TextAction selectPrevWordAction = new TextAction("Select Previous Word") {
public void actionPerformed(ActionEvent evt) {
JTextComponent c = getTextComponent(evt);
if (c == null) {
return;
}
int pos = c.getSelectionStart();
int len = c.getDocument().getLength();
try {
// Find start of previous word from selection.
// getPreviousWord() throws BadLocationException if no word precedes pos.
int start = Utilities.getPreviousWord(c, pos);
// Find end of word from start
int end = Utilities.getWordEnd(c, start);
// Set selection
c.setSelectionStart(start);
c.setSelectionEnd(end);
} catch (BadLocationException e) {
}
}
};
Related Examples
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -