JTable默认的各列宽度平均,下函数可以实现各列宽度与内容长度适应!来自互联网~
1 public void FitTableColumns(JTable myTable){
2 JTableHeader header = myTable.getTableHeader();
3 int rowCount = myTable.getRowCount();
4 Enumeration columns = myTable.getColumnModel().getColumns();
5 while(columns.hasMoreElements()){
6 TableColumn column = (TableColumn)columns.nextElement();
7 int col = header.getColumnModel().getColumnIndex(column.getIdentifier());
8 int width = (int)myTable.getTableHeader().getDefaultRenderer()
9 .getTableCellRendererComponent(myTable, column.getIdentifier()
10 , false, false, -1, col).getPreferredSize().getWidth();
11 for(int row = 0; row<rowCount; row++){
12 int preferedWidth = (int)myTable.getCellRenderer(row, col).getTableCellRendererComponent(myTable,
13 myTable.getValueAt(row, col), false, false, row, col).getPreferredSize().getWidth();
14 width = Math.max(width, preferedWidth);
15 }
16 header.setResizingColumn(column); // 此行很重要
17 column.setWidth(width+myTable.getIntercellSpacing().width);
18 }
使用方法:FitTableColumns(yourTableName);