Java examples for Swing:JTextComponent
Select Previous Word in a JTextComponent
import java.awt.event.ActionEvent; import javax.swing.text.BadLocationException; import javax.swing.text.JTextComponent; import javax.swing.text.TextAction; import javax.swing.text.Utilities; public class Main { public TextAction selectPrevWordAction = new TextAction( "Select Previous Word") { public void actionPerformed(ActionEvent evt) { JTextComponent c = getTextComponent(evt); if (c == null) { return;/*from w w w . j a va 2 s . co m*/ } int pos = c.getSelectionStart(); int len = c.getDocument().getLength(); try { 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) { } } }; }