A component that allows the user to select one or more objects from a
list. A separate model, ListModel, represents the contents
of the list. It's easy to display an array or vector of objects, using
a JList constructor that builds a ListModel
instance for you:
// Create a JList that displays the strings in data[]
String[] data = {"one", "two", "three", "four"};
JList dataList = new JList(data);
// The value of the JList model property is an object that provides
// a read-only view of the data. It was constructed automatically.
for(int i = 0; i < dataList.getModel().getSize(); i++) {
System.out.println(dataList.getModel().getElementAt(i));
}
// Create a JList that displays the superclass of JList.class.
// We store the superclasses in a java.util.Vector.
Vector superClasses = new Vector();
Class rootClass = javax.swing.JList.class;
for(Class cls = rootClass; cls != null; cls = cls.getSuperclass()) {
superClasses.addElement(cls);
}
JList classList = new JList(superClasses);
JList doesn't support scrolling directly.
To create a scrolling
list you make the JList the viewport view of a
JScrollPane. For example:
JScrollPane scrollPane = new JScrollPane(dataList);
// Or in two steps:
JScrollPane scrollPane = new JScrollPane();
scrollPane.getViewport().setView(dataList);
By default the JList selection model allows any
combination of items to be selected at a time, using the constant
MULTIPLE_INTERVAL_SELECTION.
The selection state is actually managed
by a separate delegate object, an instance of
ListSelectionModel.
However JList provides convenient properties for
managing the selection.
String[] data = {"one", "two", "three", "four"};
JList dataList = new JList(data);
dataList.setSelectedIndex(1); // select "two"
dataList.getSelectedValue(); // returns "two"
The contents of a JList can be dynamic,
in other words, the list elements can
change value and the size of the list can change after the
JList has
been created. The JList observes changes in its model with a
swing.event.ListDataListener implementation. A correct
implementation of ListModel notifies
it's listeners each time a change occurs. The changes are
characterized by a swing.event.ListDataEvent, which identifies
the range of list indices that have been modified, added, or removed.
Simple dynamic-content JList applications can use the
DefaultListModel class to store list elements. This class
implements the ListModel interface and provides the
java.util.Vector API as well. Applications that need to
provide custom ListModel implementations can subclass
AbstractListModel, which provides basic
ListDataListener support. For example:
Warning:
Serialized objects of this class will not be compatible with
future Swing releases. The current serialization support is appropriate
for short term storage or RMI between applications running the same
version of Swing. A future release of Swing will provide support for
long term persistence.
ensureIndexIsVisible(int index)
Scrolls the viewport to make the specified cell completely visible.
protected void
fireSelectionValueChanged(int firstIndex,
int lastIndex,
boolean isAdjusting)
Notifies JListListSelectionListeners that
the selection model has changed.
getCellRenderer()
Returns the object that renders the list items.
int
getFirstVisibleIndex()
Returns the index of the cell in the upper left corner of the
JList
or -1 if nothing is visible or the list is empty.
int
getFixedCellHeight()
Returns the fixed cell height value -- the value specified by setting
the fixedCellHeight property,
rather than that calculated from the list elements.
int
getFixedCellWidth()
Returns the fixed cell width value -- the value specified by setting
the fixedCellWidth property, rather than that calculated
from the list elements.
int
getLastVisibleIndex()
Returns the index of the cell in the lower right corner of the
JList
or -1 if nothing is visible or the list is empty.
int
getLeadSelectionIndex()
Returns the second index argument from the most recent
addSelectionInterval or setSelectionInterval
call.
getPrototypeCellValue()
Returns the cell width of the "prototypical cell" -- a cell used
for the calculation of cell widths, because it has the same value
as all other list items.
getScrollableTracksViewportHeight()
Returns true if this JList is displayed in a
JViewport and the viewport is taller than
JList's preferred height; otherwise returns false.
boolean
getScrollableTracksViewportWidth()
Returns true if this JList is displayed in a
JViewport and the viewport is wider than
JList's preferred width; otherwise returns false.
int
getScrollableUnitIncrement(Rectangle visibleRect,
int orientation,
int direction)
Returns the distance to scroll to expose the next or previous
row (for vertical scrolling) or character (for horizontal scrolling).
int
getSelectedIndex()
Returns the first selected index; returns -1 if there is no
selected item.
int[]
getSelectedIndices()
Returns an array of all of the selected indices in increasing
order.
setFixedCellHeight(int height)
Sets the height of every cell in the list.
void
setFixedCellWidth(int width)
Sets the width of every cell in the list.
void
setListData(Object[] listData)
Constructs a ListModel from an array of objects and then
applies setModel to it.
void
setListData(Vector listData)
Constructs a ListModel from a Vector and then
applies setModel to it.
void
setModel(ListModel model)
Sets the model that represents the contents or "value" of the
list and clears the list selection after notifying
PropertyChangeListeners.
void
setPrototypeCellValue(Object prototypeCellValue)
Computes the fixedCellWidth and
fixedCellHeight properties
by configuring the cellRenderer to index equals
zero for the specified value and then computing the renderer
component's preferred size.
setUI(ListUI ui)
Sets the look and feel (L&F) object that renders this component.
void
setValueIsAdjusting(boolean b)
Sets the data model's isAdjusting property to true,
so that a single event will be generated when all of the selection
events have finished (for example, when the mouse is being
dragged over the list in selection mode).
void
setVisibleRowCount(int visibleRowCount)
Sets the preferred number of rows in the list that can be displayed
without a scollbar, as determined by the nearest
JViewport ancestor, if any.
void
updateUI()
Sets the UI property with the "ListUI" from the current default
UIFactory.
Methods inherited from class javax.swing.JComponent
Sets the UI property with the "ListUI" from the current default
UIFactory. This method is called by the JList constructor
and to update the list's look and feel at runtime.
Returns the cell width of the "prototypical cell" -- a cell used
for the calculation of cell widths, because it has the same value
as all other list items.
public void setPrototypeCellValue(Object prototypeCellValue)
Computes the fixedCellWidth and
fixedCellHeight properties
by configuring the cellRenderer to index equals
zero for the specified value and then computing the renderer
component's preferred size. These properties are useful when the
list is too long to allow JList to compute the
width/height of each cell and there is a single cell value that is
known to occupy as much space as any of the others.
Note that we do set the fixedCellWidth and
fixedCellHeight properties here but only a
prototypeCellValue PropertyChangeEvent is fired.
To see an example which sets this property,
see the class description above.
The default value of this property is null.
This is a JavaBeans bound property.
Parameters:
prototypeCellValue - the value on which to base
fixedCellWidth and
fixedCellHeight
Sets the width of every cell in the list. If width is -1,
cell widths are computed by applying getPreferredSize
to the cellRenderer component for each list element.
The default value of this property is -1.
This is a JavaBeans bound property.
Parameters:
width - the width, in pixels, for all cells in this list
Returns the fixed cell height value -- the value specified by setting
the fixedCellHeight property,
rather than that calculated from the list elements.
Sets the height of every cell in the list. If height
is -1, cell
heights are computed by applying getPreferredSize
to the cellRenderer component for each list element.
The default value of this property is -1.
This is a JavaBeans bound property.
Parameters:
height - an integer giving the height, in pixels, for all cells
in this list
Sets the delegate that's used to paint each cell in the list. If
prototypeCellValue was set then the
fixedCellWidth and fixedCellHeight
properties are set as well. Only one PropertyChangeEvent
is generated however - for the cellRenderer property.
The default value of this property is provided by the ListUI
delegate, i.e. by the look and feel implementation.
To see an example which sets the cell renderer,
see the class description above.
This is a JavaBeans bound property.
Parameters:
cellRenderer - the ListCellRenderer
that paints list cells
public void setVisibleRowCount(int visibleRowCount)
Sets the preferred number of rows in the list that can be displayed
without a scollbar, as determined by the nearest
JViewport ancestor, if any.
The value of this property only affects the value of
the JList's preferredScrollableViewportSize.
The default value of this property is 8.
This is a JavaBeans bound property.
Parameters:
visibleRowCount - an integer specifying the preferred number of
visible rows
Returns the index of the cell in the upper left corner of the
JList
or -1 if nothing is visible or the list is empty. Note that this
cell may only be partially visible.
Returns the index of the cell in the lower right corner of the
JList
or -1 if nothing is visible or the list is empty. Note that this
cell may only be partially visible.
Returns the value of the current selection model. The selection
model handles the task of making single selections, selections
of contiguous ranges, and non-contiguous selections.
Returns:
the ListSelectionModel that implements
list selections
protected void fireSelectionValueChanged(int firstIndex,
int lastIndex,
boolean isAdjusting)
Notifies JListListSelectionListeners that
the selection model has changed. It's used to forward
ListSelectionEvents from the selectionModel
to the ListSelectionListeners added directly to the
JList.
Parameters:
firstIndex - the first selected index
lastIndex - the last selected index
isAdjusting - true if multiple changes are being made
Adds a listener to the list that's notified each time a change
to the selection occurs. Listeners added directly to the
JList
will have their ListSelectionEvent.getSource() ==
this JList
(instead of the ListSelectionModel).
Sets the selectionModel for the list to a
non-nullListSelectionModel
implementation. The selection model handles the task of making single
selections, selections of contiguous ranges, and non-contiguous
selections.
This is a JavaBeans bound property.
Parameters:
selectionModel - the ListSelectionModel that
implements the selections
Determines whether single-item or multiple-item
selections are allowed.
The following selectionMode values are allowed:
SINGLE_SELECTION
Only one list index can be selected at a time. In this
mode the setSelectionInterval and
addSelectionInterval
methods are equivalent, and only the second index
argument is used.
SINGLE_INTERVAL_SELECTION
One contiguous index interval can be selected at a time.
In this mode setSelectionInterval and
addSelectionInterval
are equivalent.
MULTIPLE_INTERVAL_SELECTION
In this mode, there's no restriction on what can be selected.
This is the default.
Parameters:
selectionMode - an integer specifying the type of selections
that are permissible
Returns the first index argument from the most recent
addSelectionModel or setSelectionInterval call.
This is a convenience method that just delegates to the
selectionModel.
Returns:
the index that most recently anchored an interval selection
Returns the second index argument from the most recent
addSelectionInterval or setSelectionInterval
call.
This is a convenience method that just delegates to the
selectionModel.
Returns:
the index that most recently ended a interval selection
Clears the selection - after calling this method
isSelectionEmpty will return true.
This is a convenience method that just delegates to the
selectionModel.
public void setSelectionInterval(int anchor,
int lead)
Selects the specified interval. Both the anchor and lead indices are
included. It's not neccessary for anchor to be less than lead.
This is a convenience method that just delegates to the
selectionModel.
public void addSelectionInterval(int anchor,
int lead)
Sets the selection to be the union of the specified interval with current
selection. Both the anchor and lead indices are
included. It's not neccessary for anchor to be less than lead.
This is a convenience method that just delegates to the
selectionModel.
public void removeSelectionInterval(int index0,
int index1)
Sets the selection to be the set difference of the specified interval
and the current selection. Both the anchor and lead indices are
removed. It's not neccessary for anchor to be less than lead.
This is a convenience method that just delegates to the
selectionModel.
Parameters:
anchor - the first index to remove from the selection
lead - the last index to remove from the selection
Sets the data model's isAdjusting property to true,
so that a single event will be generated when all of the selection
events have finished (for example, when the mouse is being
dragged over the list in selection mode).
public void setSelectedValue(Object anObject,
boolean shouldScroll)
Selects the specified object from the list.
Parameters:
anObject - the object to select
shouldScroll - true if the list should scroll to display
the selected object, if one exists; otherwise false
getPreferredScrollableViewportSize
public DimensiongetPreferredScrollableViewportSize()
Computes the size of the viewport needed to display
visibleRowCount
rows. This is trivial if
fixedCellWidth and fixedCellHeight
were specified. Note that they can be specified implicitly with
the prototypeCellValue property.
If fixedCellWidth wasn't specified,
it's computed by finding the widest list element.
If fixedCellHeight
wasn't specified then we resort to heuristics:
If the model isn't empty we just multiply the height of the first row
by visibleRowCount.
If the model is empty, (JList.getModel().getSize() == 0),
then we just allocate 16 pixels per visible row, and 256 pixels
for the width (unless fixedCellWidth was set),
and hope for the best.
public int getScrollableUnitIncrement(Rectangle visibleRect,
int orientation,
int direction)
Returns the distance to scroll to expose the next or previous
row (for vertical scrolling) or character (for horizontal scrolling).
For horizontal scrolling: return the lists font size or 1 if the font
is null.
We're using the font size instead of the width of some canonical string,
e.g. "m", because it's cheaper.
For verticaL scrolling: if we're scrolling downwards (direction is
greater than 0), and the first row is completely visible with respect
to visibleRect, then return its height. If
we're scrolling downwards and the first row is only partially visible,
return the height of the visible part of the first row. Similarly
if we're scrolling upwards we return the height of the row above
the first row, unless the first row is partially visible.
Note that the value of visibleRect must be the equal to
this.getVisibleRect().
Returns true if this JList is displayed in a
JViewport and the viewport is wider than
JList's preferred width; otherwise returns false.
If false, then don't track the viewport's width. This allows horizontal
scrolling if the JViewport is itself embedded in a
JScrollPane.
public boolean getScrollableTracksViewportHeight()
Returns true if this JList is displayed in a
JViewport and the viewport is taller than
JList's preferred height; otherwise returns false.
If false, then don't track the viewport's height. This allows vertical
scrolling if the JViewport is itself embedded in a
JScrollPane.
Returns a string representation of this JList.
This method
is intended to be used only for debugging purposes, and the
content and format of the returned string may vary between
implementations. The returned string may be empty but may not
be null.
Gets the AccessibleContext associated with this JList.
For JLists, the AccessibleContext takes the form of an
AccessibleJList.
A new AccessibleJList instance is created if necessary.
Submit a bug or feature For further API reference and developer documentation, see Java 2 SDK SE Developer Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Java, Java 2D, and JDBC are trademarks or registered trademarks of Sun Microsystems, Inc. in the US and other countries. Copyright 1993-2001 Sun Microsystems, Inc. 901 San Antonio Road Palo Alto, California, 94303, U.S.A. All Rights Reserved.