Java Swing JTable data collection not performed on last cell

I am trying to collect data from JTable using the following method in an array.

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

Everything works fine, but I can’t get the data of the last column of the last row. Error not specified. When I change the range of loops, I get an arrayoutBound error.

The return method is below:

public void setGrid(String data [][], String header []){
    dtm.setRowCount(0);
    dtm.setColumnCount(0);
    dtm.setDataVector(data, header);
    tbl1.getColumnModel().getColumn(0).setPreferredWidth(25);
}

I edited the method as shown below to get the data.

public String[][] getTableData (JTable table) {
    String dat= new String();
    DefaultTableModel dtm = (DefaultTableModel) table.getModel();
    int nRow = dtm.getRowCount(), nCol = dtm.getColumnCount();
    String[][] tableData = new String[nRow][nCol];
    for (int i = 0 ; i < nRow ; i++)
        for (int j = 0 ; j < nCol ; j++)
            dat=dat + (String) dtm.getValueAt(i,j);
            bb.Toplabel.setText("data is :" +dat);
            //tableData[i][j] = (String) dtm.getValueAt(i,j);
    return tableData;
}

The data displayed is null, even if the cell matters.

+4
source share
1 answer

, . , casting String String. String toString() Object as String , , plus (+). :

public String[][] getTableData (JTable table) {
    DefaultTableModel dtm = (DefaultTableModel) table.getModel();
    int nRow = dtm.getRowCount(), nCol = dtm.getColumnCount();
    String[][] tableData = new String[nRow][nCol];
    for (int i = 0 ; i < nRow ; i++)
        for (int j = 0 ; j < nCol ; j++) {
            String dat=""+ dtm.getValueAt(i,j);// this will be always the String
            bb.Toplabel.setText("data is :" +dat);
            tableData[i][j] = dat;
        }
    return tableData;
}

- . . , .

0

Source: https://habr.com/ru/post/1585064/


All Articles