按百分比设置JTable的列宽 [英] Set Column Width of JTable by Percentage

查看:893
本文介绍了按百分比设置JTable的列宽的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为 JTable 的几列分配固定宽度,然后为所有其他列分配相等的宽度。

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

假设 JTable 有5列。第一列宽度应为100,第二列宽度为150.如果设置两列宽度后 JTable 的剩余宽度为600,则I我想在其他三列中平均分配它。

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.

问题是 table.getParent()。getSize()。width 通常为0,即使它被添加到 JFrame 并且可见,所以我不能将它作为基础。

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.

我该如何做?

推荐答案

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

这篇关于按百分比设置JTable的列宽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆