Automatically adjust Jtable Column to fit content

孤街浪徒 提交于 2019-12-04 03:44:11

If you can use an extra library, try Swingx (https://java.net/projects/swingx) There you have a JXTable, with a method "packAll()", that does exactly what you are asking for

This is all you need:

JTable table = new JTable(){
    @Override
       public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
           Component component = super.prepareRenderer(renderer, row, column);
           int rendererWidth = component.getPreferredSize().width;
           TableColumn tableColumn = getColumnModel().getColumn(column);
           tableColumn.setPreferredWidth(Math.max(rendererWidth + getIntercellSpacing().width, tableColumn.getPreferredWidth()));
           return component;
        }
    };
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

The table will adjust each column width automatically to fit the content. There's no need to control when to trigger the resizing.

col.setWidth(width);

Read the JTable API and follow the link on How to Use Tables. In that tutorial they use the setPreferredWidth(...) to suggest a width for a column.

You may also want to check out the Table Column Adjuster which does this for you. This solution can also take into account the width of the column header.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!