Set Column Width of JTable by Percentage

后端 未结 5 1899
傲寒
傲寒 2020-12-31 20:53

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 column

5条回答
  •  无人及你
    2020-12-31 21:43

    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);
        }
    }
    

提交回复
热议问题