简体   繁体   中英

Null Pointer Exception when trying to retrieve data from JTable in Swing

I have a JTable and I wish to loop through the rows and columns of that table to retrieve each value and then add that value to a 2D array (matrix). However I get a NullPointerException when the last value in the table is attempted to be extracted. I have the following code:

DefaultTableModel dtm = (DefaultTableModel) table.getModel();
        double [][] matrix = new double[rows][cols];
        for(int i=0;i<rows;i++){
            for(int j=0;j<cols;j++){
                matrix[i][j]=Double.parseDouble((String) dtm.getValueAt(i, j));
            }
        }

Any help would be greatly appreciated

Error message Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at Inverse.actionPerformed(Inverse.java:102)

the method

dtm.getValueAt(row, column);

returns an object not an int then you are trying to cast an object into a string and then parse to a double giving you null

try this instead:

DefaultTableModel dtm = (DefaultTableModel) table.getModel();
    double [][] matrix = new double[rows][cols];
    for(int i=0;i<rows;i++){
        for(int j=0;j<cols;j++){
            matrix[i][j]=Double.parseDouble(dtm.getValueAt(i,j).toString());
        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM