自动动态调整JTable列的宽度

自动动态调整JTable列的宽度

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

问题描述

我有一个包含3列的JTable:

I have a JTable with 3 columns:

- No. #
- Name
- PhoneNumber

我想为每列设置特定的宽度,如下所示:

I want to make specific width for each column as follows:

并且我希望JTable能够在需要时动态更新其列的宽度(例如,在列#中插入大量数字)并保持JTable的相同样式

and I want the JTable able to update the widths of its columns dynamically if needed (for example, inserting large number in the column #) and keeping same style of the JTable

我使用以下代码解决了第一个问题:

I solved the first issue, using this code:

myTable.getColumnModel().getColumn(columnNumber).setPreferredWidth(columnWidth);

但是我没有成功使myTable仅在列的当前宽度不适合其内容时才动态更新宽度.您能帮我解决这个问题吗?

but I didn't success to make myTable to update the widths dynamically ONLY if the current width of the column doesn't fit its contents. Can you help me solving this issue?

推荐答案

在这里,我找到了答案:
想法是检查某些行的​​内容长度以调整列宽.
在本文中,作者在可下载的Java文件中提供了完整的代码.

Here I found my answer: http://tips4java.wordpress.com/2008/11/10/table-column-adjuster/
The idea is to check some rows' content length to adjust the column width.
In the article, the author provided a full code in a downloadable java file.

JTable table = new JTable( ... );
table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );

for (int column = 0; column < table.getColumnCount(); column++)
{
    TableColumn tableColumn = table.getColumnModel().getColumn(column);
    int preferredWidth = tableColumn.getMinWidth();
    int maxWidth = tableColumn.getMaxWidth();

    for (int row = 0; row < table.getRowCount(); row++)
    {
        TableCellRenderer cellRenderer = table.getCellRenderer(row, column);
        Component c = table.prepareRenderer(cellRenderer, row, column);
        int width = c.getPreferredSize().width + table.getIntercellSpacing().width;
        preferredWidth = Math.max(preferredWidth, width);

        //  We've exceeded the maximum width, no need to check other rows

        if (preferredWidth >= maxWidth)
        {
            preferredWidth = maxWidth;
            break;
        }
    }

    tableColumn.setPreferredWidth( preferredWidth );
}

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

07-31 10:07