abg
abg

Reputation: 2092

How do I make JScrollPane work properly with nested JTables?

The problem I have is that when more rows are added to JTable (jtbls) the vertical scrollbar doesn't appear on my JScrollPane (outer).

JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1, 4));
JScrollPane outer = new JScrollPane(panel);

jtbls = new JTable[4];
for (int i = 0; i < jtbls.length; i++) {
    jtbls[i] = new JTable(new MyTableModel());
    jtbls[i].setFillsViewportHeight(true);
    jtbls[i].setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));

    JPanel inner = new JPanel(new BorderLayout());
    inner.add(jtbls[i], BorderLayout.CENTER);
    inner.add(jtbls[i].getTableHeader(), BorderLayout.NORTH);
    inner.setPreferredSize(new Dimension(outer.getWidth() / 4, 70));

    panel.add(inner);
}

add(outer);

Screenshot

Upvotes: 1

Views: 607

Answers (2)

Catalina Island
Catalina Island

Reputation: 7126

You can set all but one of the scroll bars to VERTICAL_SCROLLBAR_NEVER and set one to VERTICAL_SCROLLBAR_ALWAYS. Then tie the scroll bar models together like @camickr showed me here.

Upvotes: 2

Xeon
Xeon

Reputation: 5989

This is because you set

inner.setPreferredSize(new Dimension(outer.getWidth() / 4, 70));

So inner JPanel is "fine" with height above 70 and don't requests more space to the parent - JPanel panel which won't request more space to its parent - JVieport.

Also if you look at the source code of JTable - method setFillsViewportHeight is only applicable to the javax.swing.JLayer, javax.swing.ScrollPaneLayout, javax.swing.ViewportLayout (look at invocations of getScrollableTracksViewportHeight()) - so this will work only when JTable is inside some viewport.

Upvotes: 1

Related Questions