JTable的列宽与内容的自适应--转

JTable的列宽与内容的自适应
JTable默认的各列宽度平均,下函数可以实现各列宽度与内容长度适应!来自互联网~

 

public void FitTableColumns(JTable myTable){
  JTableHeader header = myTable.getTableHeader();
     int rowCount = myTable.getRowCount();

     Enumeration columns = myTable.getColumnModel().getColumns();
     while(columns.hasMoreElements()){
         TableColumn column = (TableColumn)columns.nextElement();
         int col = header.getColumnModel().getColumnIndex(column.getIdentifier());
         int width = (int)myTable.getTableHeader().getDefaultRenderer()
                 .getTableCellRendererComponent(myTable, column.getIdentifier()
                         , false, false, -1, col).getPreferredSize().getWidth();
         for(int row = 0; row<rowCount; row++){
             int preferedWidth = (int)myTable.getCellRenderer(row, col).getTableCellRendererComponent(myTable,
               myTable.getValueAt(row, col), false, false, row, col).getPreferredSize().getWidth();
             width = Math.max(width, preferedWidth);
         }
         header.setResizingColumn(column); // 此行很重要
         column.setWidth(width+myTable.getIntercellSpacing().width);
     }

 

在表格数据变化后,请调用FitTableColumns(yourTableName);

网上很多,我试过,但大多不起作用,目前为止只发现这个行
原文地址:http://www.ieee.org.cn/dispbbs.asp?boardID=41&ID=52381

你可能感兴趣的:(互联网,asp)