Search code examples
javaswingjtabletablemodeldefaulttablemodel

JTable and Table model when to use when?


I have some idea about the difference between these two. But, i have some confusion about when to use when. I just know that,

  • To display a JTable create a JTable and set corresponding table model to it.
  • Any time, if we want to change the data in that table, change the data in the model, then the changes will reflect in view.

We can get the values of table from the view as well as model. This is where i am confused. If any event like (row selection) occurred, then from which i have to get the value? Is it from the view or the model? What is the best practice to use, considering the sorting and filtering of the JTable?


Solution

  • You can either get a value from the table's model, or the JTable instance itself; the end result is the same. JTable getValueAt and related methods all simply call the same method upon the internal table model object.

    JTable#getValueAt(int, int) source code:

    public Object getValueAt(int row, int column) {
        return getModel().getValueAt(convertRowIndexToModel(row),
                                     convertColumnIndexToModel(column));
    }