开发者

Column name not updating in JTable

开发者 https://www.devze.com 2023-04-05 04:34 出处:网络
I have a JTable for which I have made a table model. But on passing the column names to table model, it is not updating the column names. Can someone tell me why?

I have a JTable for which I have made a table model. But on passing the column names to table model, it is not updating the column names. Can someone tell me why?

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开发者_Go百科;
    }

    @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);
    }
}


You need to override getColumnName(int index) in your TableModel.

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号