Here you can find the source of calcColumnWidths(final JTable table)
Parameter | Description |
---|---|
table | Calculate width for this table and update column width values. |
public static void calcColumnWidths(final JTable table)
//package com.java2s; /* This file is part of the project "Hilbert II" - http://www.qedeq.org * * Copyright 2000-2013, Michael Meyling <mime@qedeq.org>. * * "Hilbert II" is free software; you can redistribute * it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */// www. j a v a2 s .com import java.awt.Component; import javax.swing.JTable; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import javax.swing.table.TableModel; public class Main { /** * Calculate table column width according to contents. See * <a href="http://www.chka.de/swing/table/cell-sizes.html">cell-sizes.html</a> * (calculating initial column widths based on contents). * * @author Christian Kaufhold * * @param table Calculate width for this table and update column width values. */ public static void calcColumnWidths(final JTable table) { final JTableHeader header = table.getTableHeader(); TableCellRenderer defaultHeaderRenderer = null; if (header != null) { defaultHeaderRenderer = header.getDefaultRenderer(); } TableColumnModel columns = table.getColumnModel(); TableModel data = table.getModel(); int margin = columns.getColumnMargin(); // only JDK1.3 int rowCount = data.getRowCount(); int totalWidth = 0; for (int i = columns.getColumnCount() - 1; i >= 0; --i) { final TableColumn column = columns.getColumn(i); final int columnIndex = column.getModelIndex(); int width = -1; TableCellRenderer h = column.getHeaderRenderer(); if (h == null) { h = defaultHeaderRenderer; } if (h != null) { // Not explicitly impossible Component c = h.getTableCellRendererComponent(table, column.getHeaderValue(), false, false, -1, i); width = c.getPreferredSize().width; } for (int row = rowCount - 1; row >= 0; --row) { TableCellRenderer r = table.getCellRenderer(row, i); Component c = r.getTableCellRendererComponent(table, data.getValueAt(row, columnIndex), false, false, row, i); width = Math.max(width, c.getPreferredSize().width); } if (width >= 0) { column.setPreferredWidth(width + margin); } else { // ??? } totalWidth += column.getPreferredWidth(); } } }