默认 table 模型的问题

Problems with default table model

我正在创建 java editable table,并遇到问题:它 "crashes" 在读取数据后。这是我的 table:

table.getTableHeader().setReorderingAllowed(false);
tableModel = new DefaultTableModel(new Object[]
{"#","1","2","3","4","5","6","7"},8);
table.setModel(tableModel);
table.getColumnModel().getColumn(0).setMaxWidth(22);

正在读取 txt:

OK4.addActionListener(new ActionListener(){
    @Override
    File f = new File(fileName);
    if(f.exists()){
        try {
            tableModel = new DefaultTableModel(new Object[]{"#","1","2","3","4","5","6","7"},0);
            BufferedReader br = new BufferedReader(new FileReader(fileName));
            String line = br.readLine();
            String[] colHeaders = line.split("\s+");
            tableModel.setColumnIdentifiers(colHeaders);
            while ((line = br.readLine()) != null) {
                String[] data = line.split("\s+");
                tableModel.addRow(data);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }else{
        JOptionPane.showMessageDialog(null, "this day is not saved");
    };
    table.setModel(tableModel);
    table.getColumnModel().getColumn(0).setMaxWidth(22);
});

导致我的总和字段的主要问题:

OK3.addActionListener(new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent e) {
        int sum=0;
        int number;
        Object smth;
        String Smth;
        int kint2 = table.getRowCount()-1;
        if(table.getValueAt(kint2, 1)=="total:"){

        }else{
            tableModel.addRow(new Object[]{});
            int a = table.getRowCount()-1;
            table.setValueAt("total:", a, 1);
        }
        for (int j = 2; j < 8; j++) {
            for (int i = 0; i < table.getRowCount()-1; i++) {
                smth = table.getValueAt(i,j);
                Smth = (String) smth;
                if (smth==null){
                    number=0;
                }else{
                    number=Integer.parseInt(Smth);
                }
                sum=sum+number;
            }
            table.setValueAt(sum, table.getRowCount()-1, j);
            sum=0;
        }
    }
});

应用程序在从 txt 读取后停止计算总和或仅计算前 4 行总和。跟我的tableModel有关系吗?

感谢您的回答。

问题是您使用 tablemodel 添加新行并使用 table 计算行数。正如在“jTable row count VS model row count”中讨论的那样,您的 table 不会更新行数,因此请始终使用 tablemodel.getRowCount()