How to Retrieve JTable Data as an Array

后端 未结 5 1312
北海茫月
北海茫月 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 13:59

    I'd like to suggest a small improvement on Manidip Sengupta's answer. Rather than casting table.getModel() to the appropriate class, it is better to simply work with TableModel. This makes the code more re-usable too (it doesn't matter which implementation of TableModel is actually being worked with).

    public Object[][] getTableData (JTable table) {
        TableModel dtm = 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;
    }
    

提交回复
热议问题