How to get the selected region in Java’s JTable?
In Java, to get the selected region using the JTable component, you can use the getSelectedRows() method to retrieve an array of selected row indexes, and then obtain the corresponding data based on those indexes.
int[] selectedRows = table.getSelectedRows();for (int i = 0; i < selectedRows.length; i++) {
int rowIndex = selectedRows[i];
// 根据行索引获取对应的数据
Object[] rowData = new Object[table.getColumnCount()];
for (int j = 0; j < table.getColumnCount(); j++) {
rowData[j] = table.getValueAt(rowIndex, j);
}
// 处理选中的数据
// ...
}
Use the getSelectedColumns() method to retrieve an array of selected column indexes, then you can fetch the corresponding data based on the column indexes.
int[] selectedColumns = table.getSelectedColumns();for (int i = 0; i < selectedColumns.length; i++) {
int columnIndex = selectedColumns[i];
// 根据列索引获取对应的数据
Object[] columnData = new Object[table.getRowCount()];
for (int j = 0; j < table.getRowCount(); j++) {
columnData[j] = table.getValueAt(j, columnIndex);
}
// 处理选中的数据
// ...
}
Use the getSelectedCells() method to retrieve an array of selected cells, and then access the corresponding data using row and column indexes.
int[] selectedRows = table.getSelectedRows();int[] selectedColumns = table.getSelectedColumns();
for (int i = 0; i < selectedRows.length; i++) {
for (int j = 0; j < selectedColumns.length; j++) {
int rowIndex = selectedRows[i];
int columnIndex = selectedColumns[j];
// 根据行列索引获取对应的数据
Object cellData = table.getValueAt(rowIndex, columnIndex);
// 处理选中的数据
// ...
}
}
The three methods mentioned above can be chosen based on the specific situation, in order to obtain data from the selected rows, columns, or cells as needed.