EarthWeb
Developer.com
Site
windows 2000
visual c++
java
visual basic
javascripts
recommend it
 
Book
thinking in java
 
Interact
forum
guest book
jobs
jokes
what's new

share code
 
Resource
add resource
modify resource
new resource
 

[Internet Jobs]
-----
Java by E-mail:

Get the weekly e-mail highlights on Java!
-----

-

Change visible columns in a JTable


Author: Vincent Oberle
Author's WebSite: http://vincent.oberle.com

Following code is a table model that allows you to specify in a boolean array the columns that must be visible.

To use it:


JTable myTable = new JTable(new MyTableModel());

The most important method in the code is getNumber(), which converts a column number (the 3rd column...) to the number corresponding to the data to show (the index in the column name array...)

Visible columns can be change dynamicaly (in a menu for instance, with


columnsVisible[nb] = menuItem.getState();)

You only need to call fireTableStructureChanged() to update the table then.


import java.util.*;
import javax.swing.*;
import javax.swing.table.*;

public class MyTableModel extends AbstractTableModel {
    
    /** Vector of Object[], this are the datas of the table */
    Vector datas = new Vector();    
    
    /** Indicates which columns are visible */
    boolean[] columnsVisible = new boolean[4];
    
    /** Column names */
    String[] columnsName = {
        "0", "1", "2", "3"
    };


    /** Constructor */        
    public MyTableModel () {
        columnsVisible[0] = true;
        columnsVisible[1] = false;
        columnsVisible[2] = true;
        columnsVisible[3] = false;
    }
    
    
    /** 
     * This functiun converts a column number in the table
     * to the right number of the datas.
     */
    protected int getNumber (int col) {
        int n = col;    // right number to return
        int i = 0;
        do {
            if (!(columnsVisible[i])) n++;
            i++;
        } while (i < n);
        // If we are on an invisible column, 
        // we have to go one step further
        while (!(columnsVisible[n])) n++;
        return n;
    }

    
    // *** TABLE MODEL METHODS ***
    
    public int getColumnCount () {
        int n = 0;
        for (int i = 0; i < 10; i++)
            if (columnsVisible[i]) n++;
        return n;
    }
    
    public int getRowCount () {
        return datas.size();
    }
    
    public Object getValueAt (int row, int col) {
        Object[] array = (Object[])(datas.elementAt(row));
        return array[getNumber(col)];
    }

    public String getColumnName (int col) {
        return columnsName[getNumber(col)];
    }
}




Posted On: 1-Aug-1999

internet.commerce



Acceptable Use Policy

WebMediaBrands

internet.comMediabistrojusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Shopping | E-mail Offers