The output from my program is in a JTextArea
inside a JScrollPane
. It looks nasty:
Created BinaryTree.java in I:\\Netbeans OLD
Check out the Table Column Adjuster.
You can set the column width based on:
The class also supports other features to allow for dynamic resizing if the data is changed.
Or you can use the basic code provided which just uses the prepareRenderer(...)
method of the JTable to determine the maximum width.
JTable table = new JTable( ... );
table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
for (int column = 0; column < table.getColumnCount(); column++)
{
TableColumn tableColumn = table.getColumnModel().getColumn(column);
int preferredWidth = tableColumn.getMinWidth();
int maxWidth = tableColumn.getMaxWidth();
for (int row = 0; row < table.getRowCount(); row++)
{
TableCellRenderer cellRenderer = table.getCellRenderer(row, column);
Component c = table.prepareRenderer(cellRenderer, row, column);
int width = c.getPreferredSize().width + table.getIntercellSpacing().width;
preferredWidth = Math.max(preferredWidth, width);
// We've exceeded the maximum width, no need to check other rows
if (preferredWidth >= maxWidth)
{
preferredWidth = maxWidth;
break;
}
}
tableColumn.setPreferredWidth( preferredWidth );
}
Edit:
I was hoping that knowing the font size and number of characters
FontMetrics fm = table.getFontMetrics( table.getFont() );
int charWidth = fm.stringWidth("a");
System.out.println( charWidth );