简体   繁体   中英

Get cell values of all selected rows in JTable

I'm trying to figure out how to iterate through the rows of a JTable and get the cell values if the row is selected (multiple rows can be selected), pass the values to a method then continue iteration. The table rows contain values entered by the user. Rows are added to the table, which is displayed in the UI one by one as the user inputs each entry. The entries consist of an int and 2 doubles. The int identifies the type and the two doubles are added to two running tallies (quantity and volume) for the type, for use elsewhere in the application. If the user selects a row (or multiple rows) and presses Delete, the rows are deleted from the table. The values of the deleted rows also need to be deducted from the running tallies. For deleting the rows, I am assigning the selected rows to an array and iterating through it to delete each row.

int[] selectedRows = entryTable.getSelectedRows();
if (selectedRows.length > 0) {
   for(int i = selectedRows.length - 1; i >= 0; i--) {
      entryTable.removeRow(selectedRows[i]); } }

If it is possible to get the cell values during this iteration, that would be ideal but after extensive searching, I have not yet found a way to do so. Any other way would be fine as long as the end result is the same. Any thoughts on the most efficient way to accomplish this would be appreciated.

Well you can try like this.

public void myMethod(JTable entryTable) {
    DefaultTableModel model = (DefaultTableModel) entryTable.getModel();
    if (entryTable.getRowCount() > 0) {
        if (entryTable.getSelectedRowCount() > 0) {
            int selectedRow[] = entryTable.getSelectedRows();
            for (int i : selectedRow) {
                int id = Integer.parseInt(entryTable.getValueAt(i, 0).toString());
                double val1 = Double.parseDouble(entryTable.getValueAt(i, 1).toString());
                double val2 = Double.parseDouble(entryTable.getValueAt(i, 2).toString());
                model.removeRow(i);
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM