简体   繁体   English

获取JTable中所有选定行的单元格值

[英]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. 我试图弄清楚如何遍历JTable的行并获取单元格值(如果选择了行(可以选择多行)),将值传递给方法,然后继续迭代。 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. 将行添加到表中,当用户输入每个条目时,该表将在UI中一一显示。 The entries consist of an int and 2 doubles. 条目包括一个int和2个双打。 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. int标识类型,并将两个双精度数添加到该类型的两个连续计数(数量和体积)中,以在应用程序中的其他位置使用。 If the user selects a row (or multiple rows) and presses Delete, the rows are deleted from the table. 如果用户选择一行(或多行)并按Delete键,则会从表中删除这些行。 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);
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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