Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Column Width of JTable by Percentage

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?

like image 518
Tom Tucker Avatar asked Sep 25 '13 18:09

Tom Tucker


1 Answers

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);
    }
}
like image 165
Carlos Parraga Avatar answered Dec 11 '22 13:12

Carlos Parraga