The Java Developers Almanac 1.4


Order this book from Amazon.

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

e921. Inserting a Column in a JTable Component

There is no insertColumn method like DefaultTableModel.insertRow() for inserting rows. In order to insert a column at a particular position, you must append the column using DefaultTable.addColumn() and then move the new column into the desired position. See e920 Appending a Column to a JTable Component and e923 Moving a Column in a JTable Component for more information.
    int rows = 10;
    int cols = 5;
    JTable table = new JTable(rows, cols);
    
    // Disable autoCreateColumnsFromModel
    table.setAutoCreateColumnsFromModel(false);
    
    // Add data
    
    // Insert a new column at position 2 (becomes 3rd column)
    insertColumn(table, "New Column", null, 2);
    
    // Insert a new column at the end
    insertColumn(table, "New Column", null, table.getColumnCount());
    
    // Creates a new column at position vColIndex
    public void insertColumn(JTable table, Object headerLabel,
                             Object[] values, int vColIndex) {
        // This method is defined in
        // e920 Appending a Column to a JTable Component
        betterAddColumn(table, headerLabel, values);
    
        table.moveColumn(table.getColumnCount()-1, vColIndex);
    }

 Related Examples
e915. Converting a Column Index Between the View and Model in a JTable Component
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
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.