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

后端 未结 3 2038
旧时难觅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 15:09

    Use key bindings instead...

    InputMap im = table.getInputMap(JTable.WHEN_FOCUSED);
    ActionMap am = table.getActionMap();
    
    im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "DeleteRow");
    am.put("DeleteRow", new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
    
            System.out.println("Delete row");
            int row = table.getSelectedRow();
    
            if (row > -1) {
    
                DefaultTableModel model = (DefaultTableModel) table.getModel();
                model.removeRow(row);
    
            }
    
        }
    });
    

    (I borrowed mKorbel data for my test, so my test was using a DefaultTableModel, you will need to cast to the model you are using).

    Also, if you editing, this may still fire, so you will need to check for that

提交回复
热议问题