Get Selected Rows Efficiently in JTable with AbstractTableModel
When using a JTable with AbstractTableModel, retrieving the selected rows can be an important task. However, the conventional approach of iterating through all rows and checking for selected cells can become inefficient when dealing with large datasets.
To address this challenge, a better approach is to update a Set of selected rows whenever a cell value changes. In the example below, we implement a TableModel that maintains a checked Set and a JList that displays the selected row numbers:
import java.util.Set; import java.util.TreeSet; import javax.swing.JTable; import javax.swing.event.TableModelListener; import javax.swing.table.AbstractTableModel; public class CheckModel extends AbstractTableModel { private int rows; private List<Boolean> rowList; private Set<Integer> checked = new TreeSet<>(); public CheckModel(int rows) { this.rows = rows; rowList = new ArrayList<>(rows); for (int i = 0; i < rows; i++) { rowList.add(Boolean.FALSE); } } @Override public void setValueAt(Object aValue, int row, int col) { boolean b = (Boolean) aValue; rowList.set(row, b); if (b) { checked.add(row); } else { checked.remove(row); } fireTableRowsUpdated(row, row); } public Set<Integer> getCheckedRows() { return checked; } }
In this model, the setValueAt method updates both the rowList and the checked Set. When a selected cell changes, a TableModelListener is notified, and the JList is updated to display the current selected rows.
This approach significantly improves performance, especially for large datasets, as it eliminates the need to traverse all rows to determine which are selected. It also allows for efficient listening to selection changes and easy retrieval of the selected rows.
The above is the detailed content of How Can I Efficiently Get Selected Rows from a JTable Using AbstractTableModel?. For more information, please follow other related articles on the PHP Chinese website!