读书人

JTable怎么设置列的宽度

发布时间: 2013-01-11 11:57:35 作者: rapoo

JTable如何设置列的宽度?
我写一个学生管理系统,里面有列,但是自动默认都是同等长度的,有些列是身份证号码需要很长,但是有些是性别,只是一个字符而已,所以我不希望性别的列和身份证列的长度一样,太占空间了,求大神指教下,有什么方法设置宽度? JDK没查到,没办法!JTable怎么设置列的宽度
[解决办法]

/**
* 自动调整表列宽度
*
* @param table 被调整表
* @param addtionalSpace 额外的宽度
* @return 总列宽
*/
public static int fitTableColumnsWidth(JTable table, int addtionalSpace) {
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JTableHeader header = table.getTableHeader();
int rowCount = table.getRowCount();

Enumeration columns = table.getColumnModel().getColumns();
int totalColumnWidth = 0;
while (columns.hasMoreElements()) {
TableColumn column = (TableColumn) columns.nextElement();
int col = header.getColumnModel().getColumnIndex(column.getIdentifier());
int width = (int) table.getTableHeader().getDefaultRenderer()
.getTableCellRendererComponent(table, column.getIdentifier()
, false, false, -1, col).getPreferredSize().getWidth();
for (int row = 0; row < rowCount; row++) {
int preferedWidth = (int) table.getCellRenderer(row, col).getTableCellRendererComponent(table,
table.getValueAt(row, col), false, false, row, col).getPreferredSize().getWidth();
width = Math.max(width, preferedWidth);
}
header.setResizingColumn(column); // this line is very important
column.setWidth(width + table.getIntercellSpacing().width + addtionalSpace);
totalColumnWidth += width + table.getIntercellSpacing().width + addtionalSpace;
}
return totalColumnWidth;
}


[解决办法]

引用:
引用:Java code
?



12345678910111213141516171819202122232425262728293031

/** * 自动调整表列宽度 * * @param table 被调整表 * @param addtionalSpace 额外……

忽略

读书人网 >J2SE开发

热点推荐