JTable: set column width based on header size

giozh picture giozh · Aug 22, 2013 · Viewed 8.9k times · Source

I have a JTable and header contains string of different type:

table = new JTable(new DefaultTableModel(info, myHeader){
        public boolean isCellEditable(int row, int column) {
            //disable table editing
            return false;
        }
    };
    header = table.getTableHeader();
    JScrollPane scroll_pane = new JScrollPane(table);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    table.getTableHeader().setReorderingAllowed(false);
    table.getTableHeader().setResizingAllowed(false);

myHeader is an array of string contains table header strings. Those strings have a different length and I'd like that column length are all equals, and that can contains the biggest string inside myHeader. In fact, now the standard columns length doesn't allow all strings to fit perfectly inside. How can I do it?

Answer

camickr picture camickr · Aug 22, 2013

Take a look at Table Column Adjuster.

You could manually invoke the getColumnHeaderWidth() method for all columns to get the maximum width (you will need to make the method public first).

Then once you know the maximum width you can manually set the width of each column. Read the Swing tutorial on Setting and Changing Column Widths for more information.