Programmatically enable editing a JTable cell on k

2019-02-20 19:08发布

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 key? I tried this link JTable edit on keypress but it doesn't work for me.

Here is my code:

public class DatabaseJTable extends JTable implements MouseListener {
    public DatabaseJTable(Object [][] data, Object [] columnNames) {
        super(data, columnNames);
        InputMap inputMap = this.getInputMap(JComponent.WHEN_FOCUSED);
        ActionMap actionMap = this.getActionMap();
        this.addMouseListener(this);

    // bind edit record to F2 key
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0), "edit");
        actionMap.put("edit", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                // TODO Auto-generated method stub
                DatabaseJTable table = (DatabaseJTable)ae.getSource();
                table.changeSelection(table.getSelectedRow(), 1, false, false);
                table.editCellAt(table.getSelectedRow(), 1);
                System.out.println("F2 pressed");
            }
        });
    // binding delete record to Delete key
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "delete");
        actionMap.put("delete", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                // TODO Auto-generated method stub

            }
        });
    }

    @Override
    public boolean isCellEditable(int row, int column) {
       return false;
    }
}

Thanks in advance.

1条回答
戒情不戒烟
2楼-- · 2019-02-20 19:29

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");
查看更多
登录 后发表回答