The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.swing.table  [62 examples] > Columns  [11 examples]

e915. 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;
    }

 Related Examples
e916. Enumerating the Columns in a JTable Component
e917. Setting the Width of a Column in a JTable Component
e918. Setting the Column Resize Mode of a JTable Component
e919. Locking the Width of a Column in a JTable Component
e920. Appending a Column to a JTable Component
e921. Inserting a Column in a JTable Component
e922. Removing a Column from a JTable Component
e923. Moving a Column in a JTable Component
e924. Allowing the User to Move a Column in a JTable Component
e925. Allowing the User to Resize a Column in a JTable Component

See also: Cells    Column Heads    Editing    Events    Layout    Rows    Scrolling    Selection    Sorting    Table Model    Tool Tips   


© 2002 Addison-Wesley.