I have a JTable that will have the last column data field change to different string values. I want to resize the column to the string length. What is the formula for string length to width?
I'm going to be using JTable.getColumnModel().getColumn().setPreferredWidth()
so I want to know how to translate string length to width value.
you are not really interested in the string length (nor its mapping to a particular font/metrics). You're interested in the preferredSize of the renderingComponent which renderers the cell content. To get that, loop through all rows and query the size, something like
int width = 0;
for (row = 0; row < table.getRowCount(); row++) {
TableCellRenderer renderer = table.getCellRenderer(row, myColumn);
Component comp = table.prepareRenderer(renderer, row, myColumn);
width = Math.max (comp.getPreferredSize().width, width);
}
Or use JXTable (in the SwingX project): it has a method pack() which does the work for you :-)
Edit: the reason to prefer the table's prepareRenderer over manually calling getXXRendererComponent on the renderer is that the table might do decorate visual properties of the renderingComponent. If those decorations effect the prefSize of the component, a manual config is off.
This method will pack a given column in a JTable -
/**
* 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 static void packColumn(JTable table, int vColIndex, int margin) {
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();
}
java.awt.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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With