1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| /**
* Size automaticaly all cells by taking the max width and the max height
* found in the content of the JTable.
*
* @param table The table to set cell sizes too
* @see #autoSizeCells(JTable, boolean, boolean)
*/
public static void autoSizeCells(JTable table) {
autoSizeCells(table, true, true);
}
/**
* Size automaticaly all cells by taking the max width and/or the max height
* found in the content of the JTable.
*
* @param table The table to set cell sizes too
* @param rwidth Resize the width of the columns (yes if true)
* @param rheight Resize the height of the columns (yes if true)
*/
public static void autoSizeCells(JTable table, boolean rwidth, boolean rheight) {
if (!rwidth && !rheight) {
return; // Should resize at least one of these properties
}
JTableHeader header = table.getTableHeader();
TableCellRenderer defaultHeaderRenderer = null;
if (header != null) {
defaultHeaderRenderer = header.getDefaultRenderer();
}
TableColumnModel columns = table.getColumnModel();
TableModel data = table.getModel();
int marginWidth = columns.getColumnMargin(); // only JDK1.3
int marginHeight = table.getRowMargin();
int rowCount = data.getRowCount();
int totalWidth = 0;
for (int i = columns.getColumnCount() - 1; i >= 0; --i) {
TableColumn column = columns.getColumn(i);
int columnIndex = column.getModelIndex();
int width = -1;
int height = -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;
height = c.getPreferredSize().height;
}
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);
if (c != null) {
width = Math.max(width, c.getPreferredSize().width);
height = Math.max(height, c.getPreferredSize().height);
}
}
if (rwidth && width >= 0) {
column.setPreferredWidth(width + marginWidth * 2);
}
if (rheight && height >= 0) {
table.setRowHeight(height + marginHeight * 2);
}
totalWidth += column.getPreferredWidth();
}
} |
Partager