not quite sure if I understood your requirement correctly (will delete it if not) ...
You can manually send an event to any component that you want to address. If necessary, send to focusOwner
- find focusOwner by querying KeyboardFocusManager
- create keyEvent with focusOwner as sender
- send this event to focusOwner
Sort of:
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);
Edit
added a few lines for actual playback with it (@Joe commented that it does not work). Clicking the button causes the action of the focused textField (it simply prints the field name here). The local context is vista and jdk6u27.
source share