向Abstract JTable模型添加一行

时间:2015-01-05 13:51:06

标签: java swing jtable abstracttablemodel

我正在尝试向我的JTable添加一行,我正在使用一个抽象方法,如下所示。我目前正从List中获取数据到setValueAt我的JTable。有没有人知道如何在不改变columnNames和数据类型的情况下向其中添加行?使用名为addRows的方法。我环顾四周,但这里没有其他问题解决了我的问题。

class MyTableModel extends AbstractTableModel {

    public String[] columnNames = {"A","B","C","D","E"};
    public Object[][] data = {
    {"Kathy", "Smith",
     "Snowboarding", new Integer(5), new Boolean(false)},
    {"John", "Doe",
     "Rowing", new Integer(3), new Boolean(true)},
    {"Sue", "Black",
     "Knitting", new Integer(2), new Boolean(false)},
    {"Jane", "White",
     "Speed reading", new Integer(20), new Boolean(true)},
    {"Joe", "Brown",
     "Pool", new Integer(10), new Boolean(false)}
    };

    public void removeRow(int row)
    {
        Object [][]newData=new Object[data.length+1][data[0].length];
        for(int i=0;i<newData.length;i++){
            for(int j=0;j<data[0].length;j++){
                newData[i][j]=data[i+1][j];
            }
        }
        data=new Object[newData.length][columnNames.length];
        data=newData;
        fireTableRowsDeleted(row, row);
    }

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

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

    public String getColumnName(int col) {
        return columnNames[col];
    }

    public Object getValueAt(int row, int col) {
        return data[row][col];
    }

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

    public boolean isCellEditable(int row, int col) {
        return col > 2;
    }

    public void setValueAt(Object value, int row, int col) { 
        data[row][col] = value;
        fireTableCellUpdated(row, col);
    }        
}

1 个答案:

答案 0 :(得分:1)

以下方法在最后添加一行:

    public void addRow(Object[] newRow) {
        data = Arrays.copyOf(data, data.length+1);
        data[data.length-1] = newRow;
        fireTableRowsInserted(data.length-1, data.length-1);
    }

像这样使用:

    model.addRow(new Object[]{"Kathy", "Smith",
                    "Snowboarding", new Integer(5), new Boolean(false)}
    );