lakshi
lakshi

Reputation: 47

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.

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 Image of student details:

https://i.sstatic.net/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 );
        }
    }

Upvotes: 0

Views: 154

Answers (1)

camickr
camickr

Reputation: 324197

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.

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.

Note if you don't want to limit the width on a column level you can just use a value like: 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. Don't change code examples unless you have a specific reason for doing so.

Upvotes: 1

Related Questions