自动调整 JTable 中的行高 [英] Auto adjust the height of rows in a JTable

查看:62
本文介绍了自动调整 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 中的行高的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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