一、Java对Jtable自动适应列宽
示例:正常情况下,Jtable默认为各列等宽,可以利用下面的方法进行设置各列数据自适应宽度
tableModel=new DefaultTableModel(); tableModel.setDataVector(data,title); table = new JTable(tableModel); FitTableColumns(table);
二、使用步骤
1.引入库
代码如下(示例):
public void FitTableColumns(JTable myTable) { //設置table的列寬隨內容調整 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); } }