列名不在JTable中更新

时间:2011-09-15 06:12:00

标签: java swing jtable

我有一个JTable,我为此制作了一个桌面模型。但是在将列名传递给表模型时,它不会更新列名。有人可以告诉我为什么吗?

class MyTableModelTwo extends AbstractTableModel {

    private Object[][] data;
    private String[] columnNames = {"Name", "ID Number", "CGPA"};

    public MyTableModelTwo(Object[][] data) {
        this.data = data;

    }

    @Override
    public int getRowCount() {
        return data.length;
    }

    @Override
    public int getColumnCount() {
        return columnNames.length;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        return data[rowIndex][columnIndex];
    }

    @Override
    public Class getColumnClass(int c) {
        return getValueAt(0, c).getClass();
    }

    @Override
    public boolean isCellEditable(int rowIndes, int columnIndex) {
        return false;
        }

    @Override
    public void setValueAt(Object value, int rowIndex, int columnIndex) {
        data[rowIndex][columnIndex] = value;
        fireTableCellUpdated(rowIndex, columnIndex);
    }
}

class MyTableTwo extends JPanel implements TableModelListener {

    private JTable table;
    private Object[][] data;
    private JTextField t;

    public MyTableTwo() {
        data = new Object[3][3];
        t = new JTextField();
        for (int i = 0; i < noElements; i++) {
            data[i][0] = "Kaushik";
            data[i][1] = "2008A3";
                data[i][2] = "7.79";
        }

        MyTableModelTwo m = new MyTableModelTwo(data);
        table = new JTable(m);

    }

    @Override
    public void tableChanged(TableModelEvent e) {
        int row = table.getRowCount();
        double sum = 0, d = 0;
        for (int i = 0; i < row; i++) {
            double c = (Double) table.getValueAt(i, 16);
            sum += c;
        }
        t.setText("" + sum);
        t.setHorizontalAlignment(JTextField.RIGHT);
    }
}

1 个答案:

答案 0 :(得分:5)

您需要覆盖TableModel中的getColumnName(int index)

@Override
public String getColumnName(int index) {
    return columnNames[index];
}