The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.swing.table  [62 examples] > Layout  [4 examples]

e950. Packing a Column of a JTable Component

This example demonstrates how to adjust the width of a column to be just wide enough to show all of the column header and the widest cell in the column.
    int rows = 3;
    int cols = 3;
    JTable table = new JTable(rows, cols);
    
    // Disable auto resizing
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    
    // Add data here
    
    // Pack the second column of the table
    int vColIndex = 1;
    int margin = 2;
    packColumn(table, vColIndex, margin);
    public void packColumns(JTable table, int margin) {
        for (int c=0; c<table.getColumnCount(); c++) {
            packColumn(table, c, 2);
        }
    }
    
    // Sets the preferred width of the visible column specified by vColIndex. The column
    // will be just wide enough to show the column head and the widest cell in the column.
    // margin pixels are added to the left and right
    // (resulting in an additional width of 2*margin pixels).
    public void packColumn(JTable table, int vColIndex, int margin) {
        TableModel model = table.getModel();
        DefaultTableColumnModel colModel = (DefaultTableColumnModel)table.getColumnModel();
        TableColumn col = colModel.getColumn(vColIndex);
        int width = 0;
    
        // Get width of column header
        TableCellRenderer renderer = col.getHeaderRenderer();
        if (renderer == null) {
            renderer = table.getTableHeader().getDefaultRenderer();
        }
        Component comp = renderer.getTableCellRendererComponent(
            table, col.getHeaderValue(), false, false, 0, 0);
        width = comp.getPreferredSize().width;
    
        // Get maximum width of column data
        for (int r=0; r<table.getRowCount(); r++) {
            renderer = table.getCellRenderer(r, vColIndex);
            comp = renderer.getTableCellRendererComponent(
                table, table.getValueAt(r, vColIndex), false, false, r, vColIndex);
            width = Math.max(width, comp.getPreferredSize().width);
        }
    
        // Add margin
        width += 2*margin;
    
        // Set the width
        col.setPreferredWidth(width);
    }

 Related Examples
e949. Packing a JTable Component
e951. Setting Grid Line Properties in a JTable Component
e952. Setting the Gap Size Between Cells in a JTable Component

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


© 2002 Addison-Wesley.