Select next word in Text Component - Java Swing

Java examples for Swing:JTextComponent

Description

Select next 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 selectNextWordAction = new TextAction("Select Next Word") {
    public void actionPerformed(ActionEvent evt) {
      JTextComponent c = getTextComponent(evt);
      if (c == null) {
        return;//from w w  w.  jav  a  2s  .  co m
      }
      int pos = c.getSelectionStart();
      int len = c.getDocument().getLength();

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

Related Tutorials