import java.util.Enumeration;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
public class Snippet {
/**
* JTable列表自适应宽度
* @param 需列表自适应宽度的JTable
*/
JFrame jf = new JFrame("简单表格");
JTable table;
//定义二维数组作为表格数据
Object[][] tableData =
{
new Object[]{"李清照" , 29 , "女"},
new Object[]{"苏格拉底", 56 , "男"},
new Object[]{"李白", 35 , "男"},
new Object[]{"弄玉", 18 , "女"},
new Object[]{"虎头" , 2 , "男"}
};
//定义一维数据作为列标题
Object[] columnTitle = {"姓名" , "年龄" , "性别"};
public void FitTableColumns() {
table = new JTable(tableData , columnTitle);//建立表格
JTableHeader header = table.getTableHeader(); //获得表头对象
int rowCount = table.getRowCount(); //获得表的行数
Enumeration columns = table.getColumnModel().getColumns(); //获得列对象,枚举类型
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); // 此行很重要
column.setWidth(width + table.getIntercellSpacing().width);
}
jf.add(new JScrollPane(table));
jf.pack();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
}
public static void main(String args[]){
new Snippet().FitTableColumns();
}
}