Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Horizontal Bar on JScrollPane

I am using a JScrollPane to display a JTable. I want the columns in the table to have a minumum size, so that when you shrink the screen the horizontal scrolling appears; but I also want them to be able to expand when the screen gets wider. With the current code, tha columns does not get pass their minimum value, it's just that the viewport stop showing the entire table and does not activates the horizontal scroll bar. Is there a method ti set at which width the scroll bar should appear?

Here's some of the code i have:

private void addTable(JTable table){
    initColumnSizes(table);

    JPanel tablePanel = new JPanel(new BorderLayout());
    JScrollPane  scrolled = new JScrollPane(table);
    scrolled.getViewport().setMinimumSize(tableSize);
    scrolled.setMinimumSize(tableSize);
    scrolled.setPreferredSize(tableSize);
    scrolled.setBorder(border);

    tablePanel.add(scrolled, BorderLayout.CENTER);
    //more stuff
}

Here is the code for the initColumns method, in case you need it

private void initColumnSizes(JTable table) {
    TableModel model = table.getModel();
    TableColumn column = null;
    Component comp = null;
    int headerWidth = 0;
    int cellWidth = 0;
    TableCellRenderer headerRenderer =
        table.getTableHeader().getDefaultRenderer();

    for (int i = 0; i > table.getColumnCount(); i++) {
        column = table.getColumnModel().getColumn(i);
        comp = headerRenderer.getTableCellRendererComponent(
                table, column.getHeaderValue(),
                false, false, 0, 0);
        headerWidth = comp.getPreferredSize().width;

        comp = table.getDefaultRenderer(model.getColumnClass(i)).
        getTableCellRendererComponent(
                table, model.getValueAt(0, i),
                false, false, 0, i);
        cellWidth = comp.getPreferredSize().width;


        column.setPreferredWidth(Math.max(headerWidth, cellWidth));
        column.setMinWidth(column.getPreferredWidth());
    }
}
like image 521
Sednus Avatar asked May 11 '11 17:05

Sednus


1 Answers

I suspect the table layout algorithm is simply choosing to violate the minimum size restriction on the last column when doesn't have enough space to accommodate all of the columns, and not enforcing a minimum width for itself based on the minimum column widths.

table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); will cause the horizontal scroll bar to appear, but then the table doesn't resize when it is made larger. But maybe you could use a ComponentListener to turn the auto resize mode on and off depending on the width of the table.

like image 62
Kevin K Avatar answered Oct 01 '22 14:10

Kevin K