Search code examples
javaswingjtabledefaulttablemodel

Replace The Value Of JTable With The Value Of Calculation Result in Java


I want to replace value of variable array in index [0][2] that the name of coloumn title is "1/y". Previous value is 0.0, I want to replace it with value of calculation result , but when I try to display it, its value is still 0.0, this my code

titleColoumn = new Object[]{"Time (Second)","Medicine", "1/y",  "x2", "X/Y", "Y^", "Error"};
                                    //0    1   2   3   4   5   6
         allData = new Double[][]  {{1.0,1.02,0.0,0.0,0.0,0.0,0.0},
                                    {2.0,0.667,0.0,0.0,0.0,0.0,0.0},
                                    {3.0,0.367,0.0,0.0,0.0,0.0,0.0},
                                    {4.0,0.278,0.0,0.0,0.0,0.0,0.0},
                                    {5.0,0.237,0.0,0.0,0.0,0.0,0.0},
                                    {6.0,0.187,0.0,0.0,0.0,0.0,0.0},
                                    {7.0,0.155,0.0,0.0,0.0,0.0,0.0},
                                    {8.0,0.156,0.0,0.0,0.0,0.0,0.0},
                                    {9.0,0.142,0.0,0.0,0.0,0.0,0.0},
                                    {10.0,0.111,0.0,0.0,0.0,0.0,0.0},
                                    {11.0,0.12,0.0,0.0,0.0,0.0,0.0},
                                    {12.0,0.097,0.0,0.0,0.0,0.0,0.0},
                                    {14.0,0.089,0.0,0.0,0.0,0.0,0.0},
                                    {15.0,0.079,0.0,0.0,0.0,0.0,0.0},
                                    {0.0,0.0,0.0,0.0,0.0,0.0,0.0}};

    tableObservation = new DefaultTableModel(allData, titleColoumn);
    table.setModel(tableObservation);

    int row,coloumn;
    //calculation 1/y
    row = 0;
    coloumn = 1;
    int inputRow = 0;
    int inputColoumn = 2;
    double onePerY;
    for(int a=0;a<allData.length;a++){
        onePerY = 1/allData[row][coloumn];
        //replace value
        allData [inputRow][inputColoumn] = onePerY;
        inputRow++;
        row++;
        System.out.println(onePerY);
    }    

What should I do, to be able to replace it ? all the assistance that you gave, I would appreciate it, thank you


Solution

  • You update array value not TableModel value. Use jTable.getModel().setValueAt() passing inputRow, inputColoumn and appropriate value for them. Your model must be editable. If you use DefaultTableModel it's editable by default.