Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize JTable column to string length?

Tags:

java

swing

jtable

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.

like image 1000
Hank Avatar asked Apr 28 '11 14:04

Hank


2 Answers

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.

like image 121
kleopatra Avatar answered Oct 01 '22 21:10

kleopatra


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);
}
like image 39
spot35 Avatar answered Oct 01 '22 22:10

spot35