Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set JScrollPane to show only a sepecific amount of rows

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());
like image 696
vedran Avatar asked Mar 22 '12 11:03

vedran


People also ask

How do I set the size of a JScrollPane?

The JScrollPane is as big as the element it holds. You should make those element(s) wider. Also, there is the setSize() -method. But you'll most likely want to use the setPreferredSize() -method as mentioned by mre.

What is the difference between JScrollPane and JScrollBar?

What are the differences between a JScrollBar and a JScrollPane in Java? A JScrollBar is a component and it doesn't handle its own events whereas a JScrollPane is a Container and it handles its own events and performs its own scrolling.

How can I tell if a row is selected in JTable?

So you can call table. getSelectionModel(). isSelectionEmpty() to find out if any row is selected.


1 Answers

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); 
like image 53
kleopatra Avatar answered Oct 02 '22 23:10

kleopatra