Passing accelerator keystrokes to the main menu in Java

952 views Asked by At

I have added some accelerators to the main menu, using MenuItem.setAccelerator(). Just basic stuff like ctrl-c for copy, etc.

This works ok. But the app is a bit like an IDE, it has several panels containing JTables. If a table cell has focus, it absorbs the accelerator key, which means the main menu never sees it.

Clearly, if an editable table cell is active I would like the cut and paste keys to function normally, but in every other case I would like the main menu to respond.

Any ideas?

2

There are 2 answers

0
Martin McBride On

Thanks, that got me on the right track.

Removing the bindings didn't quite work, it just stopped the table doing its default action so the keypress was ignored altogether.

However, adding this to the table itself worked ok:

    component.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK), "copy");
    component.getActionMap().put("copy", actions.copyAction);

(Repeated for each desired key of course). Needs to be kept in synch with any changes to the main menu itself, but I can't see a way to avoid that with any method.

0
camickr On

KeyStrokes go to the component that has focus first. Since JTable binds Ctrl+C to an Action, that action is invoked.

If you don't like the default Action of the table, then you would need to remove the binding from the table.

Read the section from the Swing tutorial on How to Use Key Bindings. It shows you how to remove a binding.