Automatically adjust Jtable column to match content

I am trying to match the width of a JTable column depending on internal data. My code is:

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 think, but the columns of the table still have the same width! The table is built into ScrollPane in GridBagLayout, is this a problem? Thanks for any suggestions.

+8
java swing jtable tablecolumn preferredsize
source share
3 answers

If you can use the additional library, try Swingx ( https://java.net/projects/swingx ) There you have JXTable, with the "packAll ()" method, which does exactly what you ask

+9
source share

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 automatically adjust each column width to match the content. There is no need to control when to start resizing.

+19
source share
 col.setWidth(width); 

Read the JTable API and follow the link How to Use Tables . In this tutorial, they use setPreferredWidth(...) to suggest the column width.

You can also check out the Table Column Adjuster , which will do this for you. This decision may also take into account the width of the column header.

+5
source share

All Articles