0

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);
            }
        }
    }

}


}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Ange King
  • 147
  • 1
  • 2
  • 12
  • I solved my data[][] issue buy using the model.getValueAt(row, col) instead.. its not great, but its a workaround that works – Ange King Oct 23 '13 at 09:24
  • Also note `data[i][j] == userFolderName` is not the appropriate way to compare strings. Always use [String.equals()](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equals%28java.lang.Object%29) method instead: `userFolderName.equals(data[i][j])`. – dic19 Oct 23 '13 at 12:07

2 Answers2

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.

blalasaadri
  • 5,990
  • 5
  • 38
  • 58
0

btw

model.setValueAt(gamesPlayed, i, j+1);

this j+1 will cause OutOfBoundsException

RamonBoza
  • 8,898
  • 6
  • 36
  • 48