Select Previous Word in a JTextComponent - Java Swing

Java examples for Swing:JTextComponent

Description

Select Previous Word in a JTextComponent

Demo Code


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) {
      }
    }
  };
}

Related Tutorials