JTable. Deleting rows. Consume the event to not get dispatched further

后端 未结 3 2061
旧时难觅i
旧时难觅i 2021-01-03 14:33

I needed to delete rows from a JTable on the delete key-press. So the use case is quite simple, the user select some rows, press the delete key, the rows get deleted. The co

3条回答
  •  無奈伤痛
    2021-01-03 14:50

    This is MadProgrammer's code but I modified it to work with multiple selected rows at once instead of one by one:

        // Assume table is a JTable instance
        InputMap inputMap = table.getInputMap(JTable.WHEN_FOCUSED);
        ActionMap actionMap = table.getActionMap();
    
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "DeleteRow");
        actionMap.put("DeleteRow", new AbstractAction()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                int[] row = table.getSelectedRows();
    
                for (int i = 0; i < row.length; i++)
                {
                    ((DefaultTableModel) table.getModel()).removeRow(row[i] - i * 1);
                }
            }
        });
    

提交回复
热议问题