Mapeando ações através de keystrokes


Esta dica de Java ilustra um método de mapear ações com keystrokes. O desenvolvedor pode usar este código para fornecer atalhos aos usuários. Por exemplo o desenvolvedor pode ajustar CTRL-U para deixar toda a palavra selecionada com letras maiúsculas, etc.

 

fig01keystroke.JPG

 

import javax.swing.*;
import javax.swing.text.*;
import java.util.Hashtable;
import java.awt.event.*;
import java.awt.BorderLayout;

public class KeymapExample {
  public static void main(String[] args) {

    JTextArea area = new JTextArea(632);
    Keymap parent = area.getKeymap();
    Keymap newmap = JTextComponent.addKeymap("KeymapExampleMap", parent);

    // CTRL-U: muda a palavra para upper case
    KeyStroke u = KeyStroke.getKeyStroke(KeyEvent.VK_U, InputEvent.CTRL_MASK);
    Action actionU = new UpWord(); 
    newmap.addActionForKeyStroke(u, actionU);

    
    Action actionList[] = area.getActions();
    
    Hashtable lookup = new Hashtable();
    for (int j=0; j < actionList.length; j+=1)
      lookup.put(actionList[j].getValue(Action.NAME), actionList[j]);

    // CTRL-L: seleciona toda a linha
    KeyStroke L = KeyStroke.getKeyStroke(KeyEvent.VK_L, InputEvent.CTRL_MASK);
    Action actionL = (Action)lookup.get(DefaultEditorKit.selectLineAction);
    newmap.addActionForKeyStroke(L, actionL);

    // CTRL-W: seleciona a palavra próxima do cursor
    KeyStroke W = KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.CTRL_MASK);
    Action actionW = (Action)lookup.get(DefaultEditorKit.selectWordAction);
    newmap.addActionForKeyStroke(W, actionW);

    area.setKeymap(newmap);

    JFrame f = new JFrame("KeymapExample");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(new JScrollPane(area), BorderLayout.CENTER);
    area.setText("This is the story\nof the hare who\nlost his spectacles.");
    f.pack();
    f.setVisible(true);
  }
 
  public static class UpWord extends TextAction {
    public UpWord() {
      super("uppercase-word-action");
    }

    public void actionPerformed(ActionEvent e) {
      JTextComponent comp = getTextComponent(e);
      if (comp == nullreturn;
      Document doc = comp.getDocument();
      int start = comp.getSelectionStart();
      int end = comp.getSelectionEnd();
      try {
        int left = javax.swing.text.Utilities.getWordStart(comp, start);
        int right = javax.swing.text.Utilities.getWordEnd(comp, end);
        String word = doc.getText(left, right-left);
        doc.remove(left, right-left);
        doc.insertString(left, word.toUpperCase(), null);
        comp.setSelectionStart(start); 
        comp.setSelectionEnd(end);
      catch (BadLocationException ble) { return; }
    }
  
}