开发者

Passing accelerator keystrokes to the main menu in Java

开发者 https://www.devze.com 2023-02-11 10:34 出处:网络
I have added some accelerators to the main menu, using MenuItem.setAccelerator(). Just basic stuff like ctrl-c for copy, etc.

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 li开发者_StackOverflow中文版ke the main menu to respond.

Any ideas?


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号