1

我想启用在一个键上编辑 JTable 单元格,比如 F2。

我知道默认情况下双击将启用编辑,但是有没有办法将该事件绑定到一个键?我在按键上尝试了此链接JTable 编辑,但它对我不起作用。

这是我的代码:

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;
    }
}

提前致谢。

4

1 回答 1

4

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");
于 2013-11-08T04:27:01.553 回答