How to Retrieve JTable Data as an Array

后端 未结 5 1306
北海茫月
北海茫月 2021-01-07 13:25

I\'ve populated a JTable through a DefaultTableModel with the (Object[][] data, String[] headers) constructor. Users can edit the table, and I want

5条回答
  •  没有蜡笔的小新
    2021-01-07 14:24

    I take that back, on 2nd thoughts, you dont need any typecasting - TableModel is an interface that has all the 3 method calls you need. :)

    Summary: Get the model for the table, check its class and typecast it to appropriate class (Abstract or Default TableModel), and use its methods to load a newly created array. Some psuedoCode:

    public Object[][] getTableData (JTable table) {
        DefaultTableModel dtm = (DefaultTableModel) table.getModel();
        int nRow = dtm.getRowCount(), nCol = dtm.getColumnCount();
        Object[][] tableData = new Object[nRow][nCol];
        for (int i = 0 ; i < nRow ; i++)
            for (int j = 0 ; j < nCol ; j++)
                tableData[i][j] = dtm.getValueAt(i,j);
        return tableData;
    }
    

    Your headers should not have changed by user-edits. Hope that helps. Regards, - M.S.

提交回复
热议问题