我正在尝试更改defaultTableModel中Object [] []数据中的值,但我在if (data[i][j] == userFolderName)
获得了nullpointerexception我尝试将变量更改为“Kathy”,以防它不是正确读取userName但它仍然抛出异常。你能看看我的代码,看看我哪里出错了吗?
public class Statistics extends JPanel {
public Object[][] data;
public DefaultTableModel model;
public Statistics() {
super(new GridLayout(1,0));
String[] columnNames = {"Name", "Games Played", "Games Won"};
Object[][] data = {
{"Kathy", new Integer(5), new Integer(2)},
{"Steve", new Integer(2), new Integer(0)},
};
model = new DefaultTableModel(data, columnNames);
JTable table = new JTable(model);
table.setFillsViewportHeight(true);
table.setVisible(true);
table.setEnabled(false);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
}
public void addRow(Object[] objects) {
model.addRow(objects);
}
public void updateGamesPlayed(String userFolderName, int gamesPlayed) {
int rowCount = model.getRowCount();
int columnCount = model.getColumnCount();
for (int i = 0; i < rowCount; i++){
for(int j = 0; j < columnCount; j++){
if (data[i][j] == userFolderName){
model.setValueAt(gamesPlayed, i, j+1);
}
}
}
}
}
答案 0 :(得分:1)
您有两个不同的data
个对象 - 构造函数中的全局对象和本地对象。如果您在构造函数中将Object[][] data = {...};
更改为data = new Object[][]{...};
,那么它应该可以正常运行,因为您只设置本地值,而不是全局值。
答案 1 :(得分:0)
顺便说一句
model.setValueAt(gamesPlayed, i, j+1);
这个j + 1会导致OutOfBoundsException