Shrink JScroll Pane to same Height as JTable

后端 未结 5 1516
独厮守ぢ
独厮守ぢ 2020-12-16 12:07

I currently have JTables nested in JScrollPanes like so:

\"enter

My problem is

5条回答
  •  猫巷女王i
    2020-12-16 12:45

    The following (currently accepted) code does not take into account various aspects of the Look and Feel:

    Dimension d = table.getPreferredSize();
    scrollPane.setPreferredSize(
        new Dimension( d.width, table.getRowHeight() * (rows+1) ));
    
    1. The header line is not necessarily table.getRowHeight() pixels in height. (In the "Metal" L&F, it is taller)
    2. A vertical scrollbar in the scrollPane will squish the table smaller than it's preferred size.
    3. A horizontal scrollbar will take additional space, so not all requested rows rows will be visible.

    The following code should be used instead:

    table.setPreferredScrollableViewportSize(
        new Dimension(
            table.getPreferredSize().width,
            table.getRowHeight() * visible_rows));
    

    The scrollPane will ask the table for its preferred size, and adds to that any extra space for the header and scrollbars.

    Below shows the difference in a JTable with 4 rows, when visible_rows is reduced from 4 to 3. The preferred width of the JScrollPane is automatically padded to include the scrollbar instead of compacting the table columns. Also note room for the header (which is different from the row height) is also automatically provided; it is not included in the visible_rows count.

提交回复
热议问题