Sets the preferred widths of the columns of a JTable to the specified percentages of the current width. - Java Swing

Java examples for Swing:JTable Column

Description

Sets the preferred widths of the columns of a JTable to the specified percentages of the current width.

Demo Code

// Licensed under the Apache License, Version 2.0 (the "License");
//package com.java2s;
import javax.swing.JTable;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

public class Main {
    /**//from   w w w . j a va  2  s.c o  m
     *  Sets the preferred widths of the columns of a table to the specified
     *  percentages of the current width. The caller may provide more or
     *  fewer values than actual columns in the table: excess values are
     *  ignored, excess columns will divide up width not assigned by the
     *  provided values (which may make them tiny). If the provided widths
     *  total more than 100%, the table will be expanded.
     */
    public static void setRelativeColumnWidths(JTable table, int... widths) {
        int tableWidth = table.getWidth();
        int usedWidth = 0;
        TableColumnModel model = table.getColumnModel();
        for (int idx = 0; idx < Math.min(widths.length,
                model.getColumnCount()); idx++) {
            TableColumn col = model.getColumn(idx);
            int colWidth = tableWidth * widths[idx] / 100;
            col.setPreferredWidth(colWidth);
            usedWidth += colWidth;
        }

        int leftover = model.getColumnCount() - widths.length;
        if (leftover <= 0)
            return;

        int colWidth = (tableWidth - usedWidth) / leftover;
        for (int idx = widths.length; idx < model.getColumnCount(); idx++) {
            TableColumn col = model.getColumn(idx);
            col.setPreferredWidth(colWidth);
        }
    }
}

Related Tutorials