[英]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). 我有一个JTable,我希望遍历该表的行和列以检索每个值,然后将该值添加到2D数组(矩阵)中。 However I get a NullPointerException when the last value in the table is attempted to be extracted.
但是,当尝试提取表中的最后一个值时,我得到了NullPointerException异常。 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 返回一个不是int的对象,然后您试图将一个对象转换为字符串,然后解析为双精度值,从而得到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());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.