简体   繁体   English

调整JTable列的宽度

[英]resize the widths of JTable's columns

I am referring this page . 我指的是这一页。 https://tips4java.wordpress.com/2008/11/10/table-column-adjuster/ to resize my column width in Jtable and it works perfectly. https://tips4java.wordpress.com/2008/11/10/table-column-adjuster/来调整我在Jtable中的列宽,并且效果很好。

But some columns are not in preferred width and can someone assistant me to find where is the problem in my code? 但是有些列的宽度不是首选的,有人可以帮助我查找代码中的问题所在吗?

I have attached the Jtable image in my project. 我已经在项目中附加了Jtable映像。

Jtable Image of student details: Jtable学生详细信息图片:

http://i.stack.imgur.com/owhW6.png

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

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

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

         tableColumn.setPreferredWidth( preferredWidth );
        }
    }

But some columns are not in preferred width 但是某些列的宽度不是首选

If you are referring to the names in the header being truncated the problem is that the code you are using only considers the data. 如果要引用的标题中的名称被截断,则问题在于所使用的代码仅考虑数据。 If you want the header width to be considered you need to use the actual TableColumnAdjuster class for full functionality. 如果要考虑标题宽度,则需要使用实际的TableColumnAdjuster类来实现全部功能。

If you are just worried about the data in each cell you still have a potential problem: 如果您只是担心每个单元格中的数据,则仍然存在潜在的问题:

int maxWidth = student_table.getColumnModel().getColumn(column).getMaxWidth();  

Did you set the maximum width of each column? 您是否设置了每列的最大宽度?

I believe the default is 75 pixels. 我相信默认值为75像素。

Note if you don't want to limit the width on a column level you can just use a value like: Integer.MAX_VALUE . 请注意,如果您不想在列级别限制宽度,则可以使用类似Integer.MAX_VALUE的值。

Also, why did you change the code from the example code found in the link? 另外,为什么还要从链接中的示例代码中更改代码? You already have a reference to the TableColumn, so why are you getting the reference again. 您已经有对TableColumn的引用,因此为什么又要获得引用。 Don't change code examples unless you have a specific reason for doing so. 除非有特殊原因,否则请勿更改代码示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM