The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.swing.table  [62 examples] > Rows  [8 examples]

e912. Copying a Row or Column in a JTable Component

This example demonstrates how to copy a column or row of data in a DefaultTableModel.
    DefaultTableModel model = new DefaultTableModel();
    JTable table = new JTable(model);
    
    // Create some data
    
    // Get all the table data
    Vector data = model.getDataVector();
    
    // Copy the second row
    Vector row = (Vector)data.elementAt(1);
    row = (Vector)row.clone();
    
    // Overwrite the first row with the copy
    Vector firstRow = (Vector)data.elementAt(0);
    for (int i=0; i<row.size(); i++) {
        firstRow.set(i, row.get(i));
    }
    
    // Append the copy to the end of the table.
    // Note that a copy is NOT made of 'row'.
    model.addRow(row);
    
    
    // Copy the first column
    int mColIndex = 0;
    java.util.List colData = new ArrayList(table.getRowCount());
    for (int i=0; i<table.getRowCount(); i++) {
        row = (Vector)data.elementAt(i);
        colData.add(row.get(mColIndex));
    }
    
    // Copy it to the second column
    for (int i=0; i<colData.size(); i++) {
        row = (Vector)data.elementAt(i);
        row.set(1, colData.get(i));
    }
    
    // Append a new column with copied data
    model.addColumn("Col3", colData.toArray());

 Related Examples
e907. Getting the Number of Rows and Columns in a JTable Component
e908. Appending a Row to a JTable Component
e909. Inserting a Row in a JTable Component
e910. Removing a Row from a JTable Component
e911. Moving a Row in a JTable Component
e913. Setting the Height of a Row in a JTable Component
e914. Shading Rows and Columns in a JTable Component

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


© 2002 Addison-Wesley.