📄 e950. packing a column of a jtable component.txt
字号:
This example demonstrates how to adjust the width of a column to be just wide enough to show all of the column header and the widest cell in the column.
int rows = 3;
int cols = 3;
JTable table = new JTable(rows, cols);
// Disable auto resizing
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
// Add data here
// Pack the second column of the table
int vColIndex = 1;
int margin = 2;
packColumn(table, vColIndex, margin);
public void packColumns(JTable table, int margin) {
for (int c=0; c<table.getColumnCount(); c++) {
packColumn(table, c, 2);
}
}
// Sets the preferred width of the visible column specified by vColIndex. The column
// will be just wide enough to show the column head and the widest cell in the column.
// margin pixels are added to the left and right
// (resulting in an additional width of 2*margin pixels).
public void packColumn(JTable table, int vColIndex, int margin) {
TableModel model = table.getModel();
DefaultTableColumnModel colModel = (DefaultTableColumnModel)table.getColumnModel();
TableColumn col = colModel.getColumn(vColIndex);
int width = 0;
// Get width of column header
TableCellRenderer renderer = col.getHeaderRenderer();
if (renderer == null) {
renderer = table.getTableHeader().getDefaultRenderer();
}
Component comp = renderer.getTableCellRendererComponent(
table, col.getHeaderValue(), false, false, 0, 0);
width = comp.getPreferredSize().width;
// Get maximum width of column data
for (int r=0; r<table.getRowCount(); r++) {
renderer = table.getCellRenderer(r, vColIndex);
comp = renderer.getTableCellRendererComponent(
table, table.getValueAt(r, vColIndex), false, false, r, vColIndex);
width = Math.max(width, comp.getPreferredSize().width);
}
// Add margin
width += 2*margin;
// Set the width
col.setPreferredWidth(width);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -