Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically adjust Jtable Column to fit content

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.

like image 562
Hans En Avatar asked Jul 25 '13 12:07

Hans En


3 Answers

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.

like image 72
Jeronimo Backes Avatar answered Nov 10 '22 02:11

Jeronimo Backes


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.

like image 38
camickr Avatar answered Nov 10 '22 01:11

camickr


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

like image 12
chipukb Avatar answered Nov 10 '22 03:11

chipukb