I am having trouble trying to set values of a Jtable: jTable1. The following method called reset, is a part of a puzzle 15 I am trying to create. This is the method that is called to assigns the values into each field of the jTable1. Assume jTable1 is already initialized so is defaulttablemodel: model. Can anyone tell me why the values won't show up when I run the code?
private void reset(){
int count=0;
String val=" "+count;
blankRow=3;
blankCol=3;
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
model.setValueAt(val,i,j);
count++;
}
}
model.setValueAt(null, blankRow, blankCol);
jTable1=new JTable(model);
jTable1.setBackground(Color.WHITE);
}
You're creating a completely new JTable object, one that is distinct from the one that is displayed. Don't do that, but instead set the model of the currently displayed JTable. This may be referenced by the jTable1 variable, but we have no way of knowing. If it does refer to the visualized JTable, then simply delete the line,
and change it to:
Note that if the model variable refers to the actual model of the displayed JTable, your whole method could be simplified to:
Also note that you will want to avoid use of magic numbers as you're using since that kind of code is very dangerous and risks index out of bounds exceptions should you change the table later.