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);
|
}
|
}
|
}
|