Select word in Text Component - Java Swing

Java examples for Swing:JTextComponent

Description

Select word in Text Component

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 selectWordAction = new TextAction("Select Word") {
    public void actionPerformed(ActionEvent evt) {
      JTextComponent c = getTextComponent(evt);
      if (c == null) {
        return;/*from   w ww .  j  a v a 2s.c  o  m*/
      }
      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 {
            start = -1;
          }
        }
        if (start != -1) {
          int end = Utilities.getWordEnd(c, start);

          // Set selection
          c.setSelectionStart(start);
          c.setSelectionEnd(end);
        }
      } catch (BadLocationException e) {
      }
    }
  };
}

Related Tutorials