Martin
Martin

Reputation: 165

JTable model column

I have a JTable and a Model for that table.

Now I want to change the order of the columns and to hide or show some columns (e.g. like Windows Explorer in "Detail View" via Menu on rightclick).

My first problem here is, the getColumnName function. Do I have to keep track of, which column is at which place and then return the right columnName or is this already part of the model? Same for the getValueAt function. Can I always return the value for the first column if I get columnIndex = 0, even if the user has dragged this column to the end of the table?

And nearly the same problem for adding/removing columns. If I do that, of course I have to fireTableStructureChanged, but do I also have to adapt e.g. the getColumnName function?

I haven't found a tutorial for that. All tutorials stop at "you can use a model". I'd really like to see an example of such a dynamic model.

Thanks a lot.

Upvotes: 0

Views: 1040

Answers (2)

camickr
camickr

Reputation: 324207

You need to understand the difference between the "View" and the "Model". When you reorder the columns in the JTable (view), this does not change the order of the data in the model.

If you want to access the first column that is displayed in the table you use:

table.getValueAt(row, 0);

if you want to access the first column in the model, then you use:

table.getModel().getValueAt(row, 0);

I want to hide or show some columns

See Table Column Manager.

Upvotes: 1

Igor Rodriguez
Igor Rodriguez

Reputation: 1246

You should use the getColumn(int) method of the model, and for accessing the model, you'll need to convert the row and column view indices with JTable's convertRowIndexToModel(int), convertColumnIndexToModel(int) and the equivalents for converting the model indices to view indices.

Upvotes: 2

Related Questions