Eng.Fouad
Eng.Fouad

Reputation: 117587

How to remove a row in JTable via pressing on DELETE on the keyboard

I know that I can use KeyListener to check if DELETE (char) 127 is pressed or not, but how can I add keyListener to the selectedRow in JTable?

EDIT:

I have tried this but it doesn't work:

myTable.addKeyListener(this);
...
public void keyPressed(KeyEvent e)
{
    if(e.getKeyCode() == 127 && myTable.GetSelectedRow() != -1)
    {
        btnRemove.doClick(); // this will remove the selected row in JTable
    }
}

Upvotes: 3

Views: 8117

Answers (3)

BullyWiiPlaza
BullyWiiPlaza

Reputation: 19195

You add the KeyListener to the JTable as follows:

table.addKeyListener(new KeyAdapter()
{
    @Override
    public void keyReleased(KeyEvent keyEvent)
    {
        considerDeletingSelectedRows(keyEvent, table);
    }
});

private void considerDeletingSelectedRows(KeyEvent keyEvent, JTable table)
{
    int keyCode = keyEvent.getKeyCode();
    int[] selectedRows = table.getSelectedRows();
    int selectedRowsCount = selectedRows.length;
    if (keyCode == KeyEvent.VK_DELETE && selectedRowsCount > 0)
    {
        // Perform actual row deletion
    }
}

For deleting selected rows, you may check out this answer.

Upvotes: 0

Brad Mace
Brad Mace

Reputation: 27886

You don't need to add one to the row. Just add one listener to the table and have it ask the table which row is selected.

You can also try keyTyped instead of keyPressed. Some platforms have had issues where one works and the other doesn't.

If you wanted to let users configure their key bindings you could as @hovercraft suggested and use key bindings. It requires mapping a KeyStroke to an action name with their InputMap and mapping the action names to Actions with their ActionMap.

table.getInputMap().put(KeyStroke.getKeyStroke("DELETE"),
                        "deleteRow");
table.getActionMap().put("deleteRow", yourAction);

Upvotes: 3

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

One issue with KeyListeners is that the component being listened to must have the focus. One way to get around this is to use Key Bindings.

e.g.,

  // assume JTable is named "table"
  int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
  InputMap inputMap = table.getInputMap(condition);
  ActionMap actionMap = table.getActionMap();

  // DELETE is a String constant that for me was defined as "Delete"
  inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), DELETE);
  actionMap.put(DELETE, new AbstractAction() {
     public void actionPerformed(ActionEvent e) {
        // TODO: do deletion action here
     }
  });

Upvotes: 11

Related Questions