1 package edu.psu.geovista.app.table;
2
3 import java.awt.Component;
4 import java.awt.Dimension;
5 import javax.swing.JTable;
6 import javax.swing.table.*;
7
8 public class MyTools {
9
10 private MyTools() {
11 }
12
13 public static void setActualPreferredColumnWidths(JTable table) {
14 int columnCount = table.getColumnCount();
15 for (int i = 0; i < columnCount; i++) {
16 TableColumn c = table.getColumnModel().getColumn(i);
17 int w = (getActualPreferredColumnWidth(c, table) * 10) / 9;
18 c.setMinWidth(w / 100);
19 c.setMaxWidth(10 * w);
20 c.setPreferredWidth(w);
21 c.setWidth(w);
22 c.setResizable(true);
23 table.setAutoResizeMode(0);
24 }
25 }
26
27 public static int getActualPreferredColumnWidth(TableColumn col, JTable table) {
28 int hw = columnHeaderWidth(col, table);
29 int cw = widestCellInColumn(col, table);
30 return hw <= cw ? cw : hw;
31 }
32
33 public static int columnHeaderWidth(TableColumn col, JTable table) {
34 TableCellRenderer renderer = col.getHeaderRenderer();
35 Component comp = renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0, 0);
36 return comp.getPreferredSize().width;
37 }
38
39 public static int widestCellInColumn(TableColumn col, JTable table) {
40 int c = col.getModelIndex();
41 int width = 0;
42 int maxw = 0;
43 for(int r = 0; r < table.getRowCount(); r++) {
44 TableCellRenderer renderer = table.getCellRenderer(r, c);
45 Component comp = renderer.getTableCellRendererComponent(table, table.getValueAt(r, c), false, false, r, c);
46 width = comp.getPreferredSize().width;
47 maxw = width <= maxw ? maxw : width;
48 }
49
50 return maxw;
51 }
52 }
This page was automatically generated by Maven