javaswingjtablecelllistselectionlistener

Listen for selection on already selected cell for JTable


Is there any way to listener for cell selection even on already selected cells with a JTable, other than using a MouseListener?


I have a JTable with a row and column listener. Neither listener fires when selecting an already selected cell:

JTable table() {
    JTable table = new JTable(10, 10);
    table.getSelectionModel().addListSelectionListener(rowListener);
    table.getColumnModel().getSelectionModel().addListSelectionListener(colListener);
    return table;
}

ListSelectionListener rowListener = event -> {
    if(event.getValueIsAdjusting())
        return;

    System.out.println("Row: "+((ListSelectionModel) event.getSource()).getMinSelectionIndex());
};

ListSelectionListener colListener = event -> {
    if(event.getValueIsAdjusting())
        return;

    System.out.println("Col: "+((ListSelectionModel) event.getSource()).getMinSelectionIndex());
};

My goal was to switch cells on/off. It works, other than the fact that the listeners do not fire when selecting an already selected cell, which is represented through the SSCCE above.

There doesn't seem to be any listener I can attach to the JTable (or it's models/selection models) to handle this, unless I were to use a MouseListener and manually manage the cooridnates. Using a TableModelListener, I can listen for changes, but this event is targeted at a previous cell (that has been deselected), and clicking an area that doesn't select a cell would cause that listener to fire.


Solution

  • My goal was to switch cells on/off.

    Store Boolean data in the TableModel. Then whenever you click on the cell the value will toggle between true/false.

    The default renderer for a Boolean value is a check box. You can always use a custom renderer if you don't want to see the check box.