Java Reference
In-Depth Information
To control the preferred number of visible rows shown, set the
visibleRowCount
property
of
JList
. The default setting for this property is 8.
Scrolling JList Components
When you're working with a
JList
component, you must place the component within a
JScrollPane
if you want to allow the user to pick from all available choices. If it's not placed
within a
JScrollPane
and the default number of rows displayed is smaller than the size of the
data model, or if there isn't sufficient space to display the rows, the other choices aren't shown.
When placed within a
JScrollPane
, the
JList
offers a vertical scrollbar to move through all the
available choices.
If you don't place a
JList
in a
JScrollPane
and the number of choices exceeds the available
space, only the top group of choices will be visible, as you can see in Figure 13-4.
Figure 13-4.
A ten-element JList, in and out of a JScrollPane
■
Tip
Whenever you see that a class implements the
Scrollable
interface, it should serve as a reminder
to place that component within a
JScrollPane
before adding it to the application.
The
JScrollPane
relies on the dimensions provided by the
preferredScrollable
➥
ViewportSize
property setting to determine the preferred size of the pane contents. When the
data model of a
JList
is empty, a default size of 16 pixels high by 256 pixels wide per visible row
is used. Otherwise, the width is determined by looping through all the cells to find the widest
one, and the height is determined by the height of the first cell.
To speed the sizing of the viewport for the
JScrollPane
, you can define a prototype cell by
setting the
prototypeCellValue
property. You must be sure the prototype
toString()
value is
sufficiently wide and tall to accommodate all the contents of the
JList
. Then the
JScrollPane
bases the sizing of its viewport on the prototype, and it won't be necessary for the
JList
to ask
each cell for its size; instead, it will ask only for the prototype.
You can also improve performance by assigning a size to the
fixedCellHeight
and
fixedCellWidth
properties. Setting these properties is another way to avoid having the
JList
ask each cell for its rendered size. Setting both properties is the fastest way to have a
JList
sized
within a viewport. Of course, this is also the least flexible because it ensures that the
JList
choices aren't widened (or shortened) when the contents change. However, if you have a large
number of entries in the data model, this loss of flexibility may be worthwhile to improve
performance. Figure 13-5 helps you to visualize some of the sizing capabilities of a
JList
.