Fix the size of a TableColumn according to the header text. - Java Swing

Java examples for Swing:JTable Column

Description

Fix the size of a TableColumn according to the header text.

Demo Code

/*//  ww  w. j  a  v  a 2  s .c  om
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
//package com.java2s;
import java.awt.Component;

import javax.swing.JTable;

import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

public class Main {
    /**
     * Fix the size of a column according to the header text.
     * 
     * @param column to be resized
     * @param table containing the column
     */
    public static void fixSize(TableColumn column, JTable table) {
        TableCellRenderer rndr;
        rndr = column.getHeaderRenderer();
        if (rndr == null) {
            rndr = table.getTableHeader().getDefaultRenderer();
        }
        Component c = rndr.getTableCellRendererComponent(table,
                column.getHeaderValue(), false, false, -1,
                column.getModelIndex());
        int width = c.getPreferredSize().width + 10;
        column.setMaxWidth(width);
        column.setPreferredWidth(width);
        column.setResizable(false);
    }
}

Related Tutorials