import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.Hashtable;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultEditorKit;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import javax.swing.text.Keymap;
import javax.swing.text.TextAction;
public class KeyListener {
public static void main(String[] args) {
JTextArea area = new JTextArea(6, 32);
Keymap parent = area.getKeymap();
Keymap newmap = JTextComponent.addKeymap("KeymapExampleMap", parent); //将一个新 keymap 添加到 keymap 层次结构。
KeyStroke u = KeyStroke.getKeyStroke(KeyEvent.VK_U,InputEvent.CTRL_MASK); //建立一个快捷键
Action actionU = new UpWord();
newmap.addActionForKeyStroke(u, actionU); //向 keymap 添加绑定。
Action actionList[] = area.getActions(); //文本域中有很多个Action
Hashtable lookup = new Hashtable();
for (int j = 0; j < actionList.length; j += 1)
lookup.put(actionList[j].getValue(Action.NAME), actionList[j]); //将每一个Action与它的名字关联,并存到哈希表中
KeyStroke L = KeyStroke.getKeyStroke(KeyEvent.VK_L,InputEvent.CTRL_MASK);
Action actionL = (Action) lookup.get(DefaultEditorKit.selectLineAction);
newmap.addActionForKeyStroke(L, actionL);
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 a test.");
f.pack();
f.setVisible(true);
}
}
//创建一个行为,该行为是使选定文本都变成大写的
class UpWord extends TextAction {
public UpWord() {
super("uppercase-word-action");
}
public void actionPerformed(ActionEvent e) {
JTextComponent comp = getTextComponent(e); //得到源组件
if (comp == null)
return;
Document doc = comp.getDocument();
int start = comp.getSelectionStart(); //选定文本的起始位置
int end = comp.getSelectionEnd();
try {
int left = javax.swing.text.Utilities.getWordStart(comp, start); //光标在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;
}
}
}