Swing: Setting a function key (F2) as an accelerator

后端 未结 2 922
时光取名叫无心
时光取名叫无心 2020-12-20 18:42

I have a menu item, \"rename\", for which F2 is set as an accelerator. Indeed when the menu is displayed there a little \"F2\" indication next to \"rename\".

Sadly,

2条回答
  •  暖寄归人
    2020-12-20 19:17

    This is probably happening because JTable uses F2 to invoke the StartEditing action (I saw the same behavior on one of my programs and traced it to this).

    There are a couple of solutions. The most drastic is to remove this input mapping (I believe this code actually removes the mapping from all JTables):

    KeyStroke keyToRemove = KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0);
    
    InputMap imap = table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    while (imap != null)
    {
        imap.remove(keyToRemove);
        imap = imap.getParent();
    }
    

    Or, if you're using the table for display only, and don't plan to let the user edit it, you could make it non-focusable:

    table.setFocusable(false);
    

    On a completely different subject, I strongly recommend creating an AbstractAction subclass for your menu items, rather than creating them "from scratch". Aside from giving you very simple menu setup code, you can use the same action instance for both the main menu and a popup/toolbar, and enable/disable them both at the same time.

提交回复
热议问题