Converting a Column Index Between the View and Model in a JTable Component

A column in a JTable component has two types of indices, a visible index and a model index. The visible index of a column is its visible location on the screen. The model index of a column is its permanent position in a TableModel, which contains the actual data. This example demonstrates how to convert a column index between the two forms.
// Converts a visible column index to a column index in the model. // Returns -1 if the index does not exist. public int toModel(JTable table, int vColIndex) { if (vColIndex >= table.getColumnCount()) { return -1; } return table.getColumnModel().getColumn(vColIndex).getModelIndex(); } // Converts a column index in the model to a visible column index. // Returns -1 if the index does not exist. public int toView(JTable table, int mColIndex) { for (int c=0; c<table.getColumnCount(); c++) { TableColumn col = table.getColumnModel().getColumn(c); if (col.getModelIndex() == mColIndex) { return c; } } return -1; }

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.