[人事管理系统] JTable的列宽与内容的自适应

来源:互联网 发布:识别图片的软件 编辑:程序博客网 时间:2024/06/09 21:31

此函数用于设置jtable的列宽与显示内容自适应,更好的利用有限的显示空间

public static void fitTableColumns(JTable myTable){myTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);int columnCount = myTable.getColumnCount();int rowCount = myTable.getRowCount();        int totalWidth = 0;for( int col = 0;col<columnCount;col++){int width = myTable.getColumnModel().getColumn(col).getPreferredWidth();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);}TableColumn column = myTable.getColumnModel().getColumn(col);myTable.getTableHeader().setResizingColumn(column); // 此行很重要column.setWidth(width+myTable.getIntercellSpacing().width*2);totalWidth += width+myTable.getIntercellSpacing().width*2;}if( myTable.getParent() == null ){return;}//如果表格实际宽度小于父容器的宽度,则让表格自适应if( totalWidth < myTable.getParent().getPreferredSize().width){myTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);}return;}


原创粉丝点击