JTable中值的总和和乘法

时间:2015-11-25 09:35:43

标签: java swing jtable sum

我无法在同一行查看每个值。它按列显示。总列线中的每个经销商都应显示所有值的总和。

我不知道如何逐行显示。

String[]entete= {"Revendeur/Montant","5000","3000","1500","800","600","500","400","REMISE","TOTAL","CREANCE"};
Object [][]donnees= {{"Patrick",0,0,0,0,0,0,0,0,0,""},
                     {"Marie",0,0,0,0,0,0,0,0,0,""},
                     {"Christian",0,0,0,0,0,0,0,0,0,""},
                     {"Fabian",0,0,0,0,0,0,0,0,0,""},
                     {"TOTAL",0,0,0,0,0,0,0,0,0,""}};
private void setTableModelListener() {
    tableModelListener = new TableModelListener() {
        public void tableChanged(TableModelEvent e) {
            int lastRow = model.getRowCount()-1 ;
            int lastColumn = model.getColumnCount()-2  ; //Colonne total
            int rowCount = model.getRowCount();

            if (e.getType() == TableModelEvent.UPDATE && e.getColumn() < lastColumn && e.getFirstRow() < lastRow && e.getLastRow() < lastRow ) {            
                int row = rowCount;
                int value = 0;// on initialise le résultat
                int value1 = 0;
                int value2 = 0;
                int value3 = 0;
                int value4 = 0;
                int value5 = 0;
                int value6 = 0;

                for (int i = 0; i < row; i++) {
                    value += 5000*(int) model.getValueAt(i, 1); // cumul montant
                    value1 += 3000*(int) model.getValueAt(i, 2); 
                    value2 += 1500*(int) model.getValueAt(i, 3); 
                    value3 += 800*(int) model.getValueAt(i, 4); 
                    value4 += 600*(int) model.getValueAt(i, 5); 
                    value5 += 500*(int) model.getValueAt(i, 6); 
                    value6 += 400*(int) model.getValueAt(i, 7); 
                }

                model.setValueAt(value, 0, lastColumn);
                model.setValueAt(value1, 1, lastColumn);
                }               
            }
      };
}

1 个答案:

答案 0 :(得分:2)

覆盖TableModel中的getValueAt(),为TOTAL行和列中的单元格返回正确的值。可以通过在循环中调用getValueAt()来计算正确的值,如TableModelListener示例中所示。在这个完整的example中,第二列每行中显示的值取决于在同一行的第三列中选择的值。