setting values in jtables

51 views Asked by At

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

There are 2 answers

1
Hovercraft Full Of Eels On

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,

// jTable1 = new JTable(model);

and change it to:

jTable1.setModel(model); // change with this

Note that if the model variable refers to the actual model of the displayed JTable, your whole method could be simplified to:

model.setRowCount(0);

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.

0
Madhan On
model.setValueAt(null, blankRow, blankCol);//If you set null value nothing wont be there obviously

jTable1=new JTable(model);//Don't do this more than one as Swing is not a thread safe 
jTable1.setBackground(Color.WHITE);//and this too

You forgot to set use val in the setValueAt

And there is no need for model to set value .You can use

jTable1.setValueAt(val, blankRow, blankCol);