0

I have a simple JTable but how can I add cellselection so that when a user left clicks with the mouse, the cell is selected. When the user selects any other cell in any other row, that cell is also selected. If the user left clicks on an already selected cell, that cell gets unselected.

Any tips would be greatly appreciated, thanks.

Souciance

2 Answers2

1

When the user selects any other cell in any other row, that selected is selected.

  • this not possible for non_continous cell selection, because ListSelectionMode is only two dimensional,

  • could be possible (never tried that) with custom Renderer and MouseListener, but then have to add /clone XxxTableModel with storing a selected cell(s), model contains only Boolean value

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
1

For something like this, what I have done myself is create an ArrayList to store the selected cells in. Then refer to that array when you need to know which cells are selected. Then I created a custom cell renderer. In that class, I would check if a cell was in the ArrayList of selected cells, and if it was I would set it to the table cell selected color.

... public class MyTableCellRenderer extends DefaultTableCellRenderer
...

        //Defined in your class somewhere
        //Add column values to it when clicked on or selected   

        private final Color selectedColumn = Color.YELLOW;
        List<String> selectedCols = new ArrayList<String>(); 

        if (selectedCols.contains(cellValue)) {
            tableCell.setBackground(selectedColumn);
        } else {
            tableCell.setBackground(UIManager.getColor("Table.background"));
        }
Logan
  • 2,369
  • 19
  • 20