ludc
2024-09-14 36c2449aec5b51e5ed4e5c6841154b746060e09a
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
package com.vci.client.ui.table;
 
import java.awt.Component;
 
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
 
/**
 * <p>Title: </p>
 * <p>Description: set width and height of table in this class according table's content</p>
 * <p>Copyright: Copyright (c) 2009</p>
 * <p>Company: VCI</p>
 * @author eddie
 * @time 2009-5-6
 * @version 1.0
 */
public class TableCellSizeAdjust {
 
    public TableCellSizeAdjust() {
        
    } 
    
    public static void setTableColumnsWidth(JTable table, int total, int rowHeight) {
        if (table == null) {
            return;
        } else {
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        }
        table.setRowHeight(rowHeight);
        int mix = total / table.getColumnCount();
        if (mix <= 0) {
            mix = 50;
        }
        setColumnPreferredWidth(table, mix);
    }
    
    private static int getColumnPreferredWidth(JTable table, int icol){
        TableColumnModel tcl = table.getColumnModel();
        TableColumn tc = tcl.getColumn(icol);
        int c = tc.getModelIndex();
        int width = 0;
        int maxw = 0;
        int row = table.getRowCount();
        for (int r = 0; r < row; r++) {
            TableCellRenderer renderer = table.getCellRenderer(r, c);
            Component comp = renderer.getTableCellRendererComponent(table, table.getValueAt(r, c), false, false, r, c);
            width = comp.getPreferredSize().width;
            maxw = width > maxw ? width : maxw;
        }
        return maxw;
    }
    
    private static void setColumnPreferredWidth(JTable table, int mix) {
        int count = table.getColumnCount();
        for (int i = 0; i < count; i++) {
            int width = getColumnPreferredWidth(table, i) + 10;
            if (width < mix) {
                width = mix;
            }
            table.getColumnModel().getColumn(i).setPreferredWidth(width);
        }
    }
}