This discussion is archived
2 Replies Latest reply: Sep 19, 2012 9:26 AM by Johnny_hunter RSS

random data in JTable model

Johnny_hunter Newbie
Currently Being Moderated
Hello all:
I am testing a JTable example, for that I create a testing data model as below:
class MyDataModel extends AbstractTableModel{
          private String columns[] = {"col1","col2","col3","col4","col5","col6","col7","col8","col9"};
          @Override
          public int getRowCount(){return 10;}
          @Override
          public int getColumnCount(){return columns.length;}
          @Override
          public Object getValueAt(int row, int col){
               Integer i = (new Random()).nextInt(100);
               return i;
          }
          @Override
          public String getColumnName(int col){ return columns[col];}

     }                    
you can see that I populated the cell with random number ranging from 0 to 100.

The table was created and number displayed as expected. However, when I click one of the cells, its data changes, as well as that in other cells, too. It looks like the data model is reloaded again and the random numbers change dynamically.
Is the setValue called somewhat? That really puzzled me.

Thanks,
Johnny
  • 1. Re: random data in JTable model
    800268 Expert
    Currently Being Moderated
    You don't populate the model with random values, instead you return a new random value each time getValueAt() is called. This is called whenever the table repaints (for example because the editing stops - note you don't actually saved the edited value, see the AbstractTableModel setValueAt implementation which is empty).
  • 2. Re: random data in JTable model
    Johnny_hunter Newbie
    Currently Being Moderated
    thanks walter

    I changed the code accordingly as below
    ...
    private Object[][] data = new Object[10][columns.length];
    MyDataModel(){
         for(int i=0;i<data.length;i++){
              for(int j=0;j<columns.length;j++){
                   data[i][j] = new Random().nextInt(100);          
              }
         }
    }
    ...
    @Override
    public Object getValueAt(int row, int col){
         return data[row][col];
    }
    didn't relized that repaint is called when a cell is clicked.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points