Creating a Custom Editing Command for a JTextComponent - Java Swing

Java examples for Swing:JTextComponent

Description

Creating a Custom Editing Command for a JTextComponent

Demo Code


import java.awt.event.ActionEvent;

import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import javax.swing.text.TextAction;

public class Main {
  public static void main(String[] args) throws Exception {
    JTextArea comp = new JTextArea();

    // Bind F2 to the lowercase action
    String actionName = "Lowercase";
    comp.getInputMap().put(KeyStroke.getKeyStroke("F2"), actionName);

    // Install the action
    comp.getActionMap().put(actionName, new TextAction(actionName) {
      public void actionPerformed(ActionEvent evt) {
        lowercaseSelection(getTextComponent(evt));
      }/*from   w  w  w.j  av a 2 s  . co m*/
    });
  }

  public static void lowercaseSelection(JTextComponent comp) {
    if (comp.getSelectionStart() == comp.getSelectionEnd()) {
      // There is no selection, only a caret
      if (comp.getCaretPosition() < comp.getDocument().getLength()) {
        try {
          int pos = comp.getCaretPosition();
          Document doc = comp.getDocument();
          String str = doc.getText(pos, 1).toLowerCase();

          doc.remove(pos, 1);
          doc.insertString(pos, str, null);
          comp.moveCaretPosition(pos + 1);
        } catch (BadLocationException e) {
        }
      }
    } else {
      // There is a selection
      int s = comp.getSelectionStart();
      int e = comp.getSelectionEnd();

      comp.replaceSelection(comp.getSelectedText().toLowerCase());
      comp.select(s, e);
    }
  }
}

Related Tutorials