I have a JTable using AbstractTableModel , where I have a JCheckBox in the first column to select rows. Now I need to get the selected rows from the table that have been checked. Right now, I sequentially traverse from the first row to the last row and get all the rows that are selected as follows:
List<Integer> selectedRows = new ArrayList<Integer>(); for(int i = 0; i < table.getRowCount(); i++) { if((Boolean) table.getValuAt(i, 0)) { selectedRows.add(i); } }
The problem here is that I need to go through all the lines when I need to get the selected lines. Now I have 10 to 20 lines. But in the future I will get about 5,000 rows. My question is: if there are 5000 rows, and if the user selects only the 5000th (last record), then I need to go through all 5000 rows to get the selected row. I think this is not a very good approach.
One approach that I want to implement is to add a listener to the JCheckBox column JCheckBox that a change (SELECTED/DESELECTED) , then I need to update my array of selected rows in the listener class. In this listener class, when the user selects the JCheckBox , I need to call table.getSelectedRow(..) , and I need to save if this JCheckBox selected.
Are there any better approaches?
source share