2

I have created a UI using Swing with a JTable. I have implemented a ListSelectionListener through which I am able to fetch records based on the selected row in the table. I am unable to deselect the row after selection.

So basically I should be able to select a row with one click and then I should be able to deselect the row with another click.

I tried using tableName.getSelectionModel.clearSelection, but I don't know how to see if a row is selected or not. What would tell me this?

Another solution I tried is using a Mouse Click Listener. Again, I am not able to write the condition to check if the mouse click happens on the previously selected row. Is there a way by which I can get the previous row selected?

I am using the DefaultTableModel.

Austin Moore
  • 1,414
  • 6
  • 20
  • 43
kirancodify
  • 695
  • 8
  • 14
  • Sure, see http://docs.oracle.com/javase/7/docs/api/javax/swing/JTable.html#getSelectedRow() or if you want to work directly with the SelectionModel http://docs.oracle.com/javase/7/docs/api/javax/swing/ListSelectionModel.html#getMinSelectionIndex() – DSquare Jul 16 '14 at 15:25
  • check this question.. http://stackoverflow.com/q/18337580/2722799 – Java Man Mar 18 '15 at 07:26

2 Answers2

5

This functionality is supported by default by holding down the "Control" key when you use the mouse click. This is the standard that is used by most applications.

If you really want to use a non standard approach then you should probably be customizing the ListSelectionModel. I would guess you would override the setSelectionInterval(...) method. That is you would first check if the row is currently selected. If so, then invoke the clearSelection() method and return. Otherwise invoke super.setSelectionInterval(...).

camickr
  • 321,443
  • 19
  • 166
  • 288
3

It may be old but this works.

table = new JTable() {
    public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend)
    {
        //Always toggle on single selection
        super.changeSelection(rowIndex, columnIndex, !extend, extend);
    }
};
fracz
  • 20,536
  • 18
  • 103
  • 149