我想在Total Column的所有单元格中显示默认表格模型总计(总和)数据

时间:2016-02-25 13:40:38

标签: java defaulttablemodel

在列总数的所有单元格中显示计算数据。

this

我不知道如何做到这一点,计算后它将显示在总列的所有单元格中。

final DefaultTableModel model = new DefaultTableModel(new String[]{"Opening", "Purchase", "Total", "Consumption"}, 10) {
    @Override
    public Object getValueAt(int row, int col) {
        Object value = null;
        switch (col) {
            case 2:
                double opening = getAmountForRow(row);
                double purchase = getCostForRow(row);
                double cons=getconsForRow(row);
                value = opening + purchase-cons;
                break;
            default:
                value = super.getValueAt(row, col);
        }
        return value;
    }

    protected double getAmountForRow(int row) {
        return getNumberForRow(row, 0);
    }

    protected double getCostForRow(int row) {
        return getNumberForRow(row, 1);
    }

    protected double getconsForRow(int row) {
        return getNumberForRow(row, 3);
    }

    protected double getNumberForRow(int row, int col) {
        double number = 0;
        Object value = getValueAt(row, col);
        if (value != null && value instanceof Number) {
            number = ((Number) value).doubleValue();
        }
        return number;
    }

    @Override
    public void setValueAt(Object aValue, int row, int column) {
        if (column != 2) {
            if (aValue instanceof Number) {
                super.setValueAt(aValue, row, column);
                if (column == 0 || column == 1 || column==3) {
                    fireTableCellUpdated(row, 2);
                }
            }
        }
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        return Double.class;
    }

    @Override
    public boolean isCellEditable(int row, int column) {
        return column != 2;
    }
};

final JTable table = new JTable(model);
table.setFillsViewportHeight(true);
table.addMouseListener(new MouseAdapter() {
    // @Override
    public void mouseClicked(MouseEvent e) {
        if (e.getClickCount() == 2) {
            if (table.rowAtPoint(e.getPoint()) < 0) {
                StringBuffer fileContent = new StringBuffer();
                model.addRow(new Vector());
            }
        }
    }
});
model.addRow(new Vector());

JFrame frame = new JFrame("Chemical");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(table));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setIconImage(null);
frame.setSize(700,500);
// frame.setFont(new Font("Tahoma", Font.PLAIN, 15));
table.setFont(new Font("Tahoma", Font.PLAIN, 20));

0 个答案:

没有答案