不能完全肯定,如果我理解正确你的要求(如不将删除此)...
您可以手动分派事件到要解决任何组件。在希望派遣到focusOwner
- 的情况下,通过查询的KeyboardFocusManager
- 创建具有focusOwner的KeyEvent发件人
- 分派该事件的focusOwner
东西找到focusOwner如:
Action action = new AbstractAction("fake enter") {
@Override
public void actionPerformed(ActionEvent e) {
KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
Component comp = manager.getFocusOwner();
KeyEvent event = new KeyEvent(comp,
KeyEvent.KEY_PRESSED, System.currentTimeMillis(), 0,
KeyEvent.VK_ENTER, KeyEvent.CHAR_UNDEFINED);
comp.dispatchKeyEvent(event);
}
};
JButton button = new JButton(action);
button.setFocusable(false);
Action textAction = new AbstractAction("text") {
@Override
public void actionPerformed(ActionEvent e) {
LOG.info("I'm the text action" + ((Component) e.getSource()).getName());
}
};
JComponent comp = Box.createVerticalBox();
for (int i = 0; i < 5; i++) {
JTextField field = new JTextField(20);
field.setName(": " + i);
field.setAction(textAction);
comp.add(field);
}
comp.add(button);
编辑
添加了一些线来实际播放它(@Joe评论它不工作)。单击该按钮将触发焦点文本字段的操作(此处仅显示字段名称)。本地上下文是vista和jdk6u27。
是否有可能使用与输入不同的组合键? Ctrl-S如果想要考虑填充字段为“保存”输入? – Thomas 2012-03-14 23:49:25
这不是不可能的,但它肯定不是优选的。我也考虑过有选项卡(即当你失去焦点时)保存数据,但我真的想保留它作为输入键。 – Joe 2012-03-14 23:52:38