Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*
 * 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);
    }
}