Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto/best fit JTable columns, but stretch the last column

Tags:

java

swing

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_RESIZE_OFF

enter image description here

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 ?

enter image description here

like image 720
Lyke Avatar asked Jun 24 '11 23:06

Lyke


1 Answers

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);
}
like image 99
Domenic D. Avatar answered Oct 19 '22 04:10

Domenic D.