自动调整JTable列宽的大小 [英] Auto resizing the JTable column widths

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

问题描述

我需要我的JTable自动重新调整其列宽以适应内容。我找到了 TableColumnAdjuster 类非常有用。但是有一个小问题。假设我有5列,其内容非常短。在这种情况下,如果我使用自动调整器,它会根据内容设置前四列宽度,并将所有剩余空间提供给最后一列。请参阅示例。

I need my JTable to automatically re-size its column widths to fit the content. I found the TableColumnAdjuster class very useful. But there's a small problem. Say i have 5 columns, and their content is very short. In that case, if i use the auto adjuster, it sets the first four columns widths according to their content and gives all the rest of space to the last column. Please see the example.

这里给出了最后一列余额所有多余的空间。但是,如果我需要将该空间提供给其中一个中间列,该怎么办呢?在上面的例子中,我需要将该空间分配给第三列, name 。我尝试修改 TableColumnAdjuster 类的 adjustColumns()方法。但我无法让它发挥作用。

Here the last column, Balance is given all the excess space. But what if i need to give that space to one of the middle columns. In the above case, i need to assign that space to the third column, name. I tried modifying the TableColumnAdjuster class's adjustColumns() method. But I couldn't get it working.

我试过 column.setPreferredWidth() column.setWidth()用于更改列大小。但似乎它没有改变任何东西。如何有效地更改 JTable 的列大小。如果对我的主要问题有其他替代或直接答案,那就更好了。谢谢!

I tried both column.setPreferredWidth() and column.setWidth() for changing column sizes. But seems it doesn't change anything. How can I effectively change the column sizes of a JTable. If there's some other alternative or a direct answer to my main problem, that's better. Thanks!

推荐答案

您可以尝试下一个:

public void resizeColumnWidth(JTable table) {
    final TableColumnModel columnModel = table.getColumnModel();
    for (int column = 0; column < table.getColumnCount(); column++) {
        int width = 15; // Min width
        for (int row = 0; row < table.getRowCount(); row++) {
            TableCellRenderer renderer = table.getCellRenderer(row, column);
            Component comp = table.prepareRenderer(renderer, row, column);
            width = Math.max(comp.getPreferredSize().width +1 , width);
        }
        if(width > 300)
            width=300;
        columnModel.getColumn(column).setPreferredWidth(width);
    }
}

这需要在调整大小方法之前执行。

如果您有:

This needs to be executed before the resize method.
If you have:

table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

这篇关于自动调整JTable列宽的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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