📄 e1001. overriding the default action of a jtextcomponent.txt
字号:
The default action in a text component keymap receives all typed characters that are not handled in any inputmap or keymap. This example demonstrates how to wrap the default action of a text component with a custom default action.
JTextArea component = new JTextArea();
Action defAction = findDefaultAction(component);
// Install the overriding default action
component.getKeymap().setDefaultAction(new MyDefaultAction(defAction));
public class MyDefaultAction extends AbstractAction {
Action defAction;
public MyDefaultAction(Action a) {
super("My Default Action");
defAction = a;
}
public void actionPerformed(ActionEvent e) {
// Perform customizations here
// This example upper cases all typed characters
if (e.getActionCommand() != null) {
String command = e.getActionCommand();
if (command != null) {
command = command.toUpperCase();
}
e = new ActionEvent(e.getSource(), e.getID(), command, e.getModifiers());
}
// Now call the installed default action
if (defAction != null) {
defAction.actionPerformed(e);
}
}
}
public Action findDefaultAction(JTextComponent c) {
// Look for default action
// Check local keymap
Keymap kmap = c.getKeymap();
if (kmap.getDefaultAction() != null) {
return kmap.getDefaultAction();
}
// Check parent keymaps
kmap = kmap.getResolveParent();
while (kmap != null) {
if (kmap.getDefaultAction() != null) {
return kmap.getDefaultAction();
}
kmap = kmap.getResolveParent();
}
return null;
}
Related Examples
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -