Java – sets the column width of JTable by percentage

I need to assign a fixed width to several columns of JTable, and then assign an equal width to all other columns

Suppose JTable has 5 columns The width of the first column shall be 100 and the width of the second column shall be 150 If the remaining width of JTable is 600 after setting the width of two columns, I want to divide it evenly among the other three columns

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

What should I do?

Solution

public MyJFrame() {
public MyJFrame() {
    initComponents();
    resizeColumns();
    addComponentListener(new ComponentAdapter() {
        @Override
        public void componentResized(ComponentEvent e) {
            resizeColumns();
        }
    });
}
//SUMS 100%
float[] columnWidthPercentage = {20.0f,55.0f,10.0f,5.0f,5.0f};

private void resizeColumns() {
    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);
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>