Auto/best fit JTable columns, but stretch the last column
I have the following JTable (Actually it's a ETable from Netbeans). It stretches across the container it's in - I'd like to keep that, and not use JTable.AUTO_RES开发者_开发技巧IZE_OFF
I'd like to fit it programatically like below, resizing each column to fit the only the cell content, or column header text and having the rightmost column fill the remaining space. How can I do that ?
You do have to set autoResize to OFF (setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
), but you also need a helper method to resize your columns.
This is inside a custom class that extends JTable, but you can just as easily reference an existing JTable:
public void resizeColumnWidth() {
int cumulativeActual = 0;
int padding = 15;
for (int columnIndex = 0; columnIndex < getColumnCount(); columnIndex++) {
int width = 50; // Min width
TableColumn column = columnModel.getColumn(columnIndex);
for (int row = 0; row < getRowCount(); row++) {
TableCellRenderer renderer = getCellRenderer(row, columnIndex);
Component comp = prepareRenderer(renderer, row, columnIndex);
width = Math.max(comp.getPreferredSize().width + padding, width);
}
if (columnIndex < getColumnCount() - 1) {
column.setPreferredWidth(width);
cumulativeActual += column.getWidth();
} else { //LAST COLUMN
//Use the parent's (viewPort) width and subtract the previous columbs actual widths.
column.setPreferredWidth((int) getParent().getSize().getWidth() - cumulativeActual);
}
}
}
Call resizeColumnWidth() whenever you add a row.
Optionally add a listener to the table so that the columns are also resized when the table itself is resized:
public MyCustomJTable() {
super();
addHierarchyBoundsListener(new HierarchyBoundsAdapter() {
@Override
public void ancestorResized(HierarchyEvent e) {
super.ancestorResized(e);
resizeColumnWidth();
}
});
setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
}
You can turn off auto resize. In this case the columns will resize automatically according to content. But in this case, if total column width is less than table's width, blank space will be there on right side. If it is greater, horizontal scroll bar will appear.
You can assign preferred width to each column using TableColumn.setPreferredWidth
. Swing will try to distribute extra space according to that. But this is also not guaranteed.
精彩评论