Java JTable Column Width Set setRelativeColumnWidths(JTable table, int... widths)

Here you can find the source of setRelativeColumnWidths(JTable table, int... widths)

Description

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

License

Apache License

Declaration

public static void setRelativeColumnWidths(JTable table, int... widths) 

Method Source Code


//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

import javax.swing.JTable;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

public class Main {
    /**/*from   ww w.java 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

  1. setMaxnimumColumnWidths(final JTable table, final int... widths)
  2. setOptimalColumnWidth(final JTable table, final int col)
  3. SetPreferedColumnWIdth(JTable table, int[] widths)
  4. setPreferredColumnWidths(final JTable table, final float[] columnWeigths, final boolean includeHeader)
  5. setPreferredRowHeights(final JTable table)
  6. setTableColWidth(JTable table, int column, int width)
  7. setTableColWidths(JTable table, int... colWidths)
  8. updateTableColumnWidth(JTable table)