简体   繁体   中英

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?

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

My rule of thumb is that I retrieve the data from the element where the change occurred (typically the source of the event). In case of your example of changes in row selection, I retrieve the data from the table, as selection is view related.

This is to avoid that I do not use the correct row/column. In the example of the row selection, it is perfectly possible that the data is sorted on the view side (in the JTable ) while the model side is not changed (the TableModel ). In that case, if I get an event that row 5 is selected, it means row 5 in the JTable and not in the TableModel .

This can be seen in the implementation of getValueAt as posted in the answer of @Vulcan. It asks the value from the model, but converts the row and column indices first from 'view-coordinates' to 'model-coordinates'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM