6

I only need a table to show 3 rows which get top 3 selling products from DB. The table is ready, but the there's a huge portion of table which is practically empty, except for 3 rows. How can I set height of this scrollpane to match the height of 3 rows?

SOLUTION:

table.setPreferredScrollableViewportSize(table.getPreferredSize());
vedran
  • 2,167
  • 9
  • 29
  • 47

1 Answers1

9

It's a quirk of the JTable's Scrollable implementation: it sets an arbitrary fixed prefScrollable size.

You null it to make the scrollPane to fall back to using the table's preferredSize:

table.setPreferredScrollableViewportSize(null);

Edit

outch, @vedran is correct, that's not always working in a core table with core layoutManagers (it was a nice hack in another question :) sorry for the confusion. Copying his comment here:

table.setPreferredScrollableViewportSize(table.getPreferredSize());

is a viable option, though all the usual bewares about hard-coding sizes apply here as well.

A well-behaved JTable would implement a more reasonable getPreferredScrollableViewportSize, f.i calculating it in terms of content. JXTable (which is the best-behaved table, biased me :-), you could set the pref in terms of visible rows, just as in a list:

xtable.setVisualRowCount(3); 
Community
  • 1
  • 1
kleopatra
  • 51,061
  • 28
  • 99
  • 211
  • +1, I guess you got it better of me again :-) , but won't setting it to null, will wipe out the whole `JTable` from the view ? – nIcE cOw Mar 22 '12 at 11:49
  • @GagandeepBali no. column names will still be visible :) – vedran Mar 22 '12 at 12:07
  • +1, please my stupid question, is there difference betweens `XxxViewportSize(table.getPreferredSize)` and yours `XxxViewportSize(null)` in the case of rows don't have got the same Height – mKorbel Mar 22 '12 at 12:07
  • Actually `table.setPreferredScrollableViewportSize(table.getPreferredSize());` will set the correct height – vedran Mar 22 '12 at 12:12
  • @mKorbel the difference is that my suggestion is _not_ working reliably, see edit :-) – kleopatra Mar 22 '12 at 12:33
  • @vedran : Actually keeping that to null, made my `JTable` display nothing. Might be the difference in LayoutManager :-) – nIcE cOw Mar 22 '12 at 13:13