问题描述
我正在尝试更改defaultTableModel中Object [] []数据中的值,但在if (data[i][j] == userFolderName)
处出现了nullpointerexception我试图将变量更改为"Kathy",以防万一它没有读取userName正确,但仍会引发异常.你能看一下我的代码,看看我出了什么问题吗?
I am trying to change a value in the Object[][] data in a defaultTableModel but I am getting a nullpointerexception at if (data[i][j] == userFolderName)
I have tried changing the variable to "Kathy" just in case it wasn't reading the userName correctly but it still throws the exception. Can you please have a look at my code and see where I'm going wrong?
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);
}
}
}
}
}
推荐答案
您有两个不同的data
对象-构造函数中的一个全局对象和一个局部对象.如果在构造函数中将Object[][] data = {...};
更改为data = new Object[][]{...};
,则它应该可以工作,因为您只设置本地值,而不是全局值.
You have two different data
objects - a global one and a local one in your constructor. If you change Object[][] data = {...};
to data = new Object[][]{...};
in your constructor it should work as you're only setting the local one, not the global value.
这篇关于setValueAt(Object aValue,int row,int col)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!