I have a simple wish for my Swing UI: there is a standard Copy action that is mapped to the InputMap
of a component. Next there is a popup menu in this same component and I would like to add a menu item that runs the copy action and of course would show the keyboard shortcut that is in the inputMap.
This is the mac-version of the mapping, which I finally managed to add as a generic rule with the help of this, by realising that some components use "copy", whereas others use DefaultEditorKit.copyAction:
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.META_DOWN_MASK), DefaultEditorKit.copyAction);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.META_DOWN_MASK), "copy");
Now, I can find the action for a table, for example with
ActionMap actionMap = myTable.getActionMap();
Action action = actionMap.get("copy");
Now, I use the Action to create the MenuItem:
JPopupMenu popupMenu = new JPopupMenu();
JMenuItem item = new JMenuItem(action);
popupMenu.add(item);
table.setComponentPopupMenu(popupMenu);
As a result, I see the menu item, but it does not copy anything, although the shortcut key that is mapped to the same action, does copy. I can even define the shortcut (which I seemingly have to define myself, but also just as a hint for the user that these things are somehow linked together):
int MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_C, MASK);
item.setAccelerator(keyStroke);
So, what am I missing? I even tried to define the action listener specifically, to no avail:
item.addActionListener(myTable.getActionForKeyStroke(keyStroke));
Sounds funny that the keyboard shortcut works automatically (I just had to figure out how to make the Cmd-key work in Mac instead of Ctrl (which took only a couple of hours)) and now I cannot make the menu entry linked to the existing action by no means (even after working for another couple of hours).