I have a JTable
using AbstractTableModel
where I have a JCheckBox
in the first column for selecting rows. Now, I need to get the selected rows from the table which are checked. Right now, I am sequentially traversing from first row to the last row and getting all the rows that are selected like the following,
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, I need to traverse all the rows when ever I need to get the selected rows. Right now I am having 10 to 20 rows. But in future I will get around 5000 rows. My question is, if there are 5000 rows and if the user selects only 5000nd (last record) row then I need to traverse all the 5000 rows to get the selected row. Which I think is not a good approach.
One approach which I want to implement is, to add a listener to the JCheckBox
column, such that when ever there is a change (SELECTED/DESELECTED)
then I need to update my array of the selected rows in the listener class. In this listener class when ever user selectes a JCheckBox
I need to call table.getSelectedRow(..)
and I need to store if that JCheckBox
is selected.
Are there any better approaches ?