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

问题描述

在JTable中,如何让一些行自动增加高度以显示内部的完整多行文字?这就是目前的显示方式:

In a JTable, how can I make some rows automatically increase height to show the complete multiline text inside? This is how it is displayed at the moment:

我不想为所有行设置高度,但仅限于具有多行文字的行。

I do not want to set the height for all rows, but only for the ones which have multiline text.

推荐答案

确定行高的唯一方法是渲染每个单元格以确定渲染高度。在您的表格填充数据后,您可以执行以下操作:

The only way to know the row height for sure is to render each cell to determine the rendered height. After your table is populated with data you can do:

private void updateRowHeights()
{
    for (int row = 0; row < table.getRowCount(); row++)
    {
        int rowHeight = table.getRowHeight();

        for (int column = 0; column < table.getColumnCount(); column++)
        {
            Component comp = table.prepareRenderer(table.getCellRenderer(row, column), row, column);
            rowHeight = Math.max(rowHeight, comp.getPreferredSize().height);
        }

        table.setRowHeight(row, rowHeight);
    }
}

如果只有第一列可以包含多行,你可以仅针对该列优化上述代码。

If only the first column can contain multiple line you can optimize the above code for that column only.

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

08-31 01:15