Programmatically enable editing a JTable cell on keystroke

前端 未结 1 545
情书的邮戳
情书的邮戳 2021-01-17 04:36

I would like to enable editing a JTable cell on a key, say F2.

I know that by default double clicking will enable editing, but is there a way to bind that event to a

相关标签:
1条回答
  • 2021-01-17 04:57

    F2 already is the default KeyStroke used by JTable to start editing.

    See Key Bindings for a table of all the KeyStrokes used by all the components. You will also find examples of using key bindings.

    If you do create you own Action, instead of using the provide Action then the code should be something like:

    int row = table.getSelectedRow();
    int column = table.getSelectedColumn();
    
    if (editCellAt(row, column))
    {
        Component editor = table.getEditorComponent();
        editor.requestFocusInWindow();
    }
    

    So the editor gets focus once the key is pressed.

    Apparently, Aqua LAF doesn't bind F2 so it looks like you need to do it yourself. Assuming the "startEditing" Action is defined in the ActionMap you can use:

    KeyStroke keyStroke = KeyStroke.getKeyStroke("F2");
    InputMap im = table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    im.put(keystroke, "startEditing");
    
    0 讨论(0)
提交回复
热议问题