问题
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);
}
}
}
}
}
回答1:
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.
回答2:
btw
model.setValueAt(gamesPlayed, i, j+1);
this j+1 will cause OutOfBoundsException
来源:https://stackoverflow.com/questions/19537533/setvalueatobject-avalue-int-row-int-col