不完全确定我是否正确理解你的要求(如果没有,将删除)…
您可以手动将事件分派给要解决的任何组件.在想要派遣到focusOwner的情况下
>通过查询KeyboardFocusManager找到focusOwner
>使用focusOwner作为发件人创建一个keyEvent
>将该事件发送到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评论说它不起作用).单击该按钮会触发焦点textField的操作(此处只是打印出字段的名称)本地上下文是vista和jdk6u27.