Set Column Width of JTable by Percentage

Tom Tucker picture Tom Tucker · Sep 25, 2013 · Viewed 23k times · Source

I need to assign a fixed width to a few columns of a JTable and then an equal width to all the other columns.

Suppose a JTable has 5 columns. The first column should have a width of 100 and the second one a width of 150. If the remaining width of the JTable is 600 after setting the width of the two columns, I'd like to evenly split it among the other three columns.

The problem is table.getParent().getSize().width is often 0, even if it is added to the JFrame and visible, so I can't use it as a basis.

How do I go about doing this?

Answer

Carlos Parraga picture Carlos Parraga · Sep 25, 2014
public MyJFrame() {
    initComponents();
    resizeColumns();
    addComponentListener(new ComponentAdapter() {
        @Override
        public void componentResized(ComponentEvent e) {
            resizeColumns();
        }
    });
}
//SUMS 1
float[] columnWidthPercentage = {0.2f, 0.55f, 0.1f, 0.05f, 0.05f, 0.05f};

private void resizeColumns() {
    // Use TableColumnModel.getTotalColumnWidth() if your table is included in a JScrollPane
    int tW = jTable1.getWidth();
    TableColumn column;
    TableColumnModel jTableColumnModel = jTable1.getColumnModel();
    int cantCols = jTableColumnModel.getColumnCount();
    for (int i = 0; i < cantCols; i++) {
        column = jTableColumnModel.getColumn(i);
        int pWidth = Math.round(columnWidthPercentage[i] * tW);
        column.setPreferredWidth(pWidth);
    }
}