开发者

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

开发者 https://www.devze.com 2023-03-15 13:08 出处:网络
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 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

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

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 ?

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消