Swing面板上调整JTable的行高和列宽,以及表格超出JScorllPane时设置滚动条

时间:2023-01-26 22:53:19
//设置列宽:适应单元格内容
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 + 10);
}
}

设置行高:

    jTable.setRowHeight(25);


此种方式会导致,当列宽超出JScorllPane大小时,不出现滚动条。此时需要设置:

jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);