Home > Enterprise >  How to individually set the width of a row on a table/scrollpane
How to individually set the width of a row on a table/scrollpane

Time:07-03

i have a DefaultTableModel:

DefaultTableModel model = new DefaultTableModel(data, beschriftung)
        {
            //  Returning the Class of each column will allow different
            //  renderers to be used based on Class
            public Class getColumnClass(int column)
            {
                return getValueAt(0, column).getClass();
            }
        };

This is inside a table:

JTable table = new JTable(model);
        table.setEnabled(false);
        table.setRowHeight(50);

And the table is inside a scrollPane:

JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setBounds(1215, 11, 300, 300);
        scrollPane.setWheelScrollingEnabled(true);
        scrollPane.setEnabled(false);
        getContentPane().add(scrollPane);

I have two rows, but want the first one to be shorter than the second one. Any suggestions?

This is how it looks like:

https://img.codepudding.com/202207/000da007551149cd825f0086e714da3c.png

This is how I want it to look like:

https://img.codepudding.com/202207/cacbd13c64c34a30beff34a4277b2d1e.png

CodePudding user response:

Check out:

  1. Check of the section from the Swing tutorial on Setting and Changing Columns Widths. It shows how you can manually set a preferred size for each column.

The basic code would be:

table.getColumnModel().getColumn(???).setPreferredWidth(???)
  1. You can also check out the Table Column Adjuster for automatic sizing of columns based on the data contained in the model

The basic code for this approach is:

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 );
}

The TableColumnAdjuster class in the link contains other features as well.

Also check out the JTable API for the setAutoResizeMode(...) method to determine how space is allocated if the width of the table changes.

  • Related