Tuesday, July 19, 2011

Override Del key action in JTable

    /**
     * This method aims at capturing the DELETE key stroke so as to remove
     * the corresponding selected row in the table.
     */
    private void doDelAction() {

        final KeyStroke delStroke = KeyStroke.getKeyStroke("DELETE");
        Action newDelAction =
            new AbstractAction("") {
                public void actionPerformed(ActionEvent e) {
                    final int selectedRow =
                        JguiEditList.this.table.getSelectedRow();
                    // If a row is selected.
                    if ((-1 != selectedRow) &&
                        (JguiEditList.this.table.getRowCount() - 1 !=
                         selectedRow)) {
                        JguiEditList.this.model.removeRow(selectedRow);
                        JguiEditList.this.table.setRowSelectionInterval(
                            selectedRow, selectedRow);
                    }
                }
            };
        this.table.getInputMap(JComponent.WHEN_FOCUSED).put(delStroke,
                                                            "EmptyRowAction");
        this.table.getActionMap().put("EmptyRowAction", newDelAction);
    }