Java JTable Column Width Set adjustColumnWidth(JTable table, int buf)

Here you can find the source of adjustColumnWidth(JTable table, int buf)

Description

adjust Column Width

License

Apache License

Declaration

public static void adjustColumnWidth(JTable table, int buf) 

Method Source Code

//package com.java2s;
/*//from   w w  w . j av  a  2  s . co m
 * Copyright 2014 kohii.
 * 
 * Licensed 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.
 */

import java.awt.Component;

import javax.swing.JTable;

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

public class Main {
    public static void adjustColumnWidth(JTable table) {
        adjustColumnWidth(table, 2);
    }

    public static void adjustColumnWidth(JTable table, int buf) {
        int columncount = table.getColumnCount();
        for (int i = 0; i < columncount; i++) {
            sizeWidthToFitData(table, i, buf);
        }
    }

    public static void sizeWidthToFitData(JTable table, int vc, int buf) {
        TableColumn tc = table.getColumnModel().getColumn(vc);

        int max = table.getTableHeader().getDefaultRenderer()
                .getTableCellRendererComponent(table, tc.getHeaderValue(), false, false, 0, vc)
                .getPreferredSize().width;

        int vrows = table.getRowCount();
        for (int i = 0; i < vrows; i++) {
            TableCellRenderer r = table.getCellRenderer(i, vc);
            Object value = table.getValueAt(i, vc);
            Component c = r.getTableCellRendererComponent(table, value, false, false, i, vc);
            int w = c.getPreferredSize().width;
            if (max < w) {
                max = w;
            }
        }

        tc.setPreferredWidth(max + buf);
    }
}

Related

  1. adjustColumnPreferredWidths(JTable table)
  2. adjustColumnPreferredWidths(JTable table)
  3. adjustColumnWidth(JTable tbl, int col, int maxColumnWidth)
  4. adjustColumnWidth(TableModel model, int columnIndex, int maxWidth, int rightPadding, JTable table)
  5. adjustColWidth(JTable table, int firstColumnWidth, int middleColumnWidth, int lastColumnWidth, int padding)
  6. autoFitColumnWidth(JTable table, TableColumn tableColumn)