Search code examples
javaswingjtableabstracttablemodel

Adding a row to Abstract JTable model


I am trying to add a row to my JTable, I am using an abstract method which is shown below. I am currently taking data from a List to setValueAt my JTable. Does anyone have any idea on how to add a row to this without changing the types of columnNames and data? Using a method called addRows that is. I have looked around but no other questions on here solved my problem.

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

Solution

  • The following method adds a row at the end:

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

    Use it like this:

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