Automatically adjust Jtable Column to fit content

java, jtable, preferredsize, swing, tablecolumn

Solution

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

Problem

I am trying to match the JTable column width depending on the data inside. My Code: ``` for(int column = 0; column < gui.testsuiteInfoTable.getColumnCount(); column ++){ int width =0; for (int row = 0; row < gui.testsuiteInfoTable.getRowCount(); row++) { TableCellRenderer renderer = gui.testsuiteInfoTable.getCellRenderer(row, column); Component comp = gui.testsuiteInfoTable.prepareRenderer(renderer, row, column); width = Math.max (comp.getPreferredSize().width, width); System.out.println(width); } TableColumn col = new TableColumn(); col = gui.testsuiteInfoTable.getColumnModel().getColumn(column); System.out.println(width); col.setWidth(width); gui.testsuiteInfoTable.revalidate(); } } ``` The sizes are correct I guess but the table columns still all have the same width! The table is embedded in a ScrollPane in a GridBagLayout is that the problem? Thanks for any suggestions.

Original source