ListModel
, maintains the
contents of the list.
It's easy to display an array or Vector of objects, using the JList
constructor that automatically builds a read-only ListModel
instance
for you:
// Create a JList that displays strings from an array
String[] data = {"one", "two", "three", "four"};
JList<String> myList = new JList<String>(data);
// Create a JList that displays the superclasses of JList.class, by
// creating it with a Vector populated with this data
Vector<Class<?>> superClasses = new Vector<Class<?>>();
Class<JList> rootClass = javax.swing.JList.class;
for(Class<?> cls = rootClass; cls != null; cls = cls.getSuperclass()) {
superClasses.addElement(cls);
}
JList<Class<?>> myList = new JList<Class<?>>(superClasses);
// The automatically created model is stored in JList's "model"
// property, which you can retrieve
ListModel<Class<?>> model = myList.getModel();
for(int i = 0; i < model.getSize(); i++) {
System.out.println(model.getElementAt(i));
}
A ListModel
can be supplied directly to a JList
by way of a
constructor or the setModel
method. The contents need not be static -
the number of items, and the values of items can change over time. A correct
ListModel
implementation notifies the set of
javax.swing.event.ListDataListener
s that have been added to it, each
time a change occurs. These changes are characterized by a
javax.swing.event.ListDataEvent
, which identifies the range of list
indices that have been modified, added, or removed. JList
's
ListUI
is responsible for keeping the visual representation up to
date with changes, by listening to the model.
Simple, dynamic-content, JList
applications can use the
DefaultListModel
class to maintain list elements. This class
implements the ListModel
interface and also provides a
java.util.Vector
-like API. Applications that need a more
custom ListModel
implementation may instead wish to subclass
AbstractListModel
, which provides basic support for managing and
notifying listeners. For example, a read-only implementation of
AbstractListModel
:
// This list model has about 2^16 elements. Enjoy scrolling.
ListModel<String> bigData = new AbstractListModel<String>() {
public int getSize() { return Short.MAX_VALUE; }
public String getElementAt(int index) { return "Index " + index; }
};
The selection state of a JList
is managed by another separate
model, an instance of ListSelectionModel
. JList
is
initialized with a selection model on construction, and also contains
methods to query or set this selection model. Additionally, JList
provides convenient methods for easily managing the selection. These methods,
such as setSelectedIndex
and getSelectedValue
, are cover
methods that take care of the details of interacting with the selection
model. By default, JList
's selection model is configured to allow any
combination of items to be selected at a time; selection mode
MULTIPLE_INTERVAL_SELECTION
. The selection mode can be changed
on the selection model directly, or via JList
's cover method.
Responsibility for updating the selection model in response to user gestures
lies with the list's ListUI
.
A correct ListSelectionModel
implementation notifies the set of
javax.swing.event.ListSelectionListener
s that have been added to it
each time a change to the selection occurs. These changes are characterized
by a javax.swing.event.ListSelectionEvent
, which identifies the range
of the selection change.
The preferred way to listen for changes in list selection is to add
ListSelectionListener
s directly to the JList
. JList
then takes care of listening to the selection model and notifying your
listeners of change.
Responsibility for listening to selection changes in order to keep the list's
visual representation up to date lies with the list's ListUI
.
Painting of cells in a JList
is handled by a delegate called a
cell renderer, installed on the list as the cellRenderer
property.
The renderer provides a java.awt.Component
that is used
like a "rubber stamp" to paint the cells. Each time a cell needs to be
painted, the list's ListUI
asks the cell renderer for the component,
moves it into place, and has it paint the contents of the cell by way of its
paint
method. A default cell renderer, which uses a JLabel
component to render, is installed by the lists's ListUI
. You can
substitute your own renderer using code like this:
// Display an icon and a string for each object in the list.
class MyCellRenderer extends JLabel implements ListCellRenderer<Object> {
static final ImageIcon longIcon = new ImageIcon("long.gif");
static final ImageIcon shortIcon = new ImageIcon("short.gif");
// This is the only method defined by ListCellRenderer.
// We just reconfigure the JLabel each time we're called.
public Component getListCellRendererComponent(
JList<?> list, // the list
Object value, // value to display
int index, // cell index
boolean isSelected, // is the cell selected
boolean cellHasFocus) // does the cell have focus
{
String s = value.toString();
setText(s);
setIcon((s.length() > 10) ? longIcon : shortIcon);
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
setEnabled(list.isEnabled());
setFont(list.getFont());
setOpaque(true);
return this;
}
}
myList.setCellRenderer(new MyCellRenderer());
Another job for the cell renderer is in helping to determine sizing
information for the list. By default, the list's ListUI
determines
the size of cells by asking the cell renderer for its preferred
size for each list item. This can be expensive for large lists of items.
To avoid these calculations, you can set a fixedCellWidth
and
fixedCellHeight
on the list, or have these values calculated
automatically based on a single prototype value:
JList<String> bigDataList = new JList<String>(bigData);
// We don't want the JList implementation to compute the width
// or height of all of the list cells, so we give it a string
// that's as big as we'll need for any cell. It uses this to
// compute values for the fixedCellWidth and fixedCellHeight
// properties.
bigDataList.setPrototypeCellValue("Index 1234567890");
JList
doesn't implement scrolling directly. To create a list that
scrolls, make it the viewport view of a JScrollPane
. For example:
JScrollPane scrollPane = new JScrollPane(myList); // Or in two steps: JScrollPane scrollPane = new JScrollPane(); scrollPane.getViewport().setView(myList);
JList
doesn't provide any special handling of double or triple
(or N) mouse clicks, but it's easy to add a MouseListener
if you
wish to take action on these events. Use the locationToIndex
method to determine what cell was clicked. For example:
MouseListener mouseListener = new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { int index = list.locationToIndex(e.getPoint()); System.out.println("Double clicked on Item " + index); } } }; list.addMouseListener(mouseListener);
Warning
Swing is not thread safe. For more information see Swing's Threading Policy.
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. As of 1.4, support for long term storage
of all JavaBeans
has been added to the java.beans
package.
Please see java.
.
See How to Use Lists in The Java Tutorial for further documentation.
ListModel
, AbstractListModel
, DefaultListModel
, ListSelectionModel
, DefaultListSelectionModel
, ListCellRenderer
, DefaultListCellRenderer
Modifier and Type | Class and Description |
---|---|
protected class | JList.
This class implements accessibility support for the
|
public static class | JList.
A subclass of |
private class |
Modifier and Type | Field and Description |
---|---|
private ListCellRenderer | |
private ListModel | |
private boolean | |
private transient JList. | dropLocation
The drop location. |
private DropMode | dropMode
The drop mode for this component. |
private int | |
private int | |
public static final int | HORIZONTAL_WRAP
Indicates a "newspaper style" layout with cells flowing horizontally then vertically. |
private int | |
private int | layoutOrientation
How to lay out the cells; defaults to |
private E | |
private Color | |
private Color | |
private ListSelectionListener | |
private ListSelectionModel | |
private static final String | |
private transient boolean | updateInProgress
Flag to indicate UI update is in progress |
public static final int | VERTICAL
Indicates a vertical layout of cells, in a single column; the default layout. |
public static final int | VERTICAL_WRAP
Indicates a "newspaper style" layout with cells flowing vertically then horizontally. |
private int |
Access | Constructor and Description |
---|---|
public | |
public | JList(final E[]
the array of Objects to be loaded into the data model,
listData)non-null Constructs a |
public | |
public |
Modifier and Type | Method and Description |
---|---|
public void | addListSelectionListener(ListSelectionListener
the listener)ListSelectionListener to addAdds a listener to the list, to be notified each time a change to the selection occurs; the preferred way of listening for selection state changes. |
public void | addSelectionInterval(int
the first index to add to the selection anchor, int the last index to add to the selection lead)Sets the selection to be the union of the specified interval with current selection. |
private void | checkScrollableParameters(Rectangle visibleRect, int orientation)
--- The Scrollable Implementation --- |
public void | |
protected ListSelectionModel | Returns: aDefaultListSelectionModel , used to initialize
the list's selection model property during constructionReturns an instance of |
pack-priv JList. | Returns: the drop location, ornull the point to calculate a drop location for p)Overrides javax. |
public void | ensureIndexIsVisible(int
the index of the cell to make visible index)Scrolls the list within an enclosing viewport to make the specified cell completely visible. |
protected void | fireSelectionValueChanged(int
the first index in the range, firstIndex, int <= lastIndex the last index in the range, lastIndex, boolean >= firstIndex whether or not this is one in a series of
multiple events, where changes are still being made isAdjusting)Notifies |
public AccessibleContext | Returns: anAccessibleJList that serves as the
AccessibleContext of this JList Overrides java. Implements javax. AccessibleContext associated with this JList .
|
public int | |
public Rectangle | Returns: the bounding rectangle for the range of cells, ornull the first index in the range index0, int the second index in the range index1)Returns the bounding rectangle, in the list's coordinate system, for the range of cells specified by the two indices. |
public ListCellRenderer | Returns: the value of thecellRenderer propertyReturns the object responsible for painting list items. |
public boolean | Returns: the value of thedragEnabled propertyReturns whether or not automatic drag handling is enabled. |
public final JList. | Returns: the drop locationReturns the location that this component should visually indicate
as the drop location during a DnD operation over the component,
or |
public final DropMode | |
public int | Returns: the index of the first visible cellReturns the smallest list index that is currently visible. |
public int | Returns: the fixed cell heightReturns the value of the |
public int | |
public int | Returns: the index of the last visible cellReturns the largest list index that is currently visible. |
public int | Returns: the value of thelayoutOrientation propertyReturns the layout orientation property for the list: |
public int | |
public ListSelectionListener[] | Returns: all of theListSelectionListener s on this list, or
an empty array if no listeners have been addedReturns an array of all the |
public int | Returns: the largest selected cell indexReturns the largest selected cell index, or |
public int | Returns: the smallest selected cell index, or-1 Returns the smallest selected cell index, or |
public ListModel | Returns: theListModel that provides the displayed
list of itemsReturns the data model that holds the list of items displayed
by the |
public int | Returns: the index of the next list element that starts with the prefix; otherwise-1 the string to test for a match prefix, int the index for starting the search startIndex, Position.the search direction, either
Position.Bias.Forward or Position.Bias.Backward. biasReturns the next list element whose |
public Dimension | Returns: a dimension containing the size of the viewport needed to displayvisibleRowCount rowsImplements javax. visibleRowCount
rows.
|
public E | Returns: the value of theprototypeCellValue propertyReturns the "prototypical" cell value -- a value used to calculate a fixed width and height for cells. |
public int | Returns: the "block" increment for scrolling in the specified direction; always positivethe view area visible within the viewport visibleRect, int SwingConstants.HORIZONTAL or
SwingConstants.VERTICAL less or equal to zero to scroll up/back,
greater than zero for down/forward direction)Implements javax. |
public boolean | Returns: whether or not an enclosing viewport should force the list's height to match its ownImplements javax. true if this JList is displayed in a
JViewport and the viewport is taller than the list's
preferred height, or if the layout orientation is VERTICAL_WRAP
and visibleRowCount <= 0 ; otherwise returns false .
|
public boolean | Returns: whether or not an enclosing viewport should force the list's width to match its ownImplements javax. true if this JList is displayed in a
JViewport and the viewport is wider than the list's
preferred width, or if the layout orientation is HORIZONTAL_WRAP
and visibleRowCount <= 0 ; otherwise returns false .
|
public int | Returns: the "unit" increment for scrolling in the specified direction; always positivethe view area visible within the viewport visibleRect, int SwingConstants.HORIZONTAL or
SwingConstants.VERTICAL less or equal to zero to scroll up/back,
greater than zero for down/forward direction)Implements javax. |
public int | Returns: the smallest selected cell indexReturns the smallest selected cell index; the selection when only a single item is selected in the list. |
public int[] | Returns: all of the selected indices, in increasing order, or an empty array if nothing is selectedReturns an array of all of the selected indices, in increasing order. |
public E | Returns: the first selected valueReturns the value for the smallest selected cell index; the selected value when only a single item is selected in the list. |
public Object[] | Returns: the selected values, or an empty array if nothing is selected
Deprecated
As of JDK 1.7, replaced by
Returns an array of all the selected values, in increasing order based
on their indices in the list.
getSelectedValuesList()
|
public List | Returns: the selected items, or an empty list if nothing is selectedReturns a list of all the selected items, in increasing order based on their indices in the list. |
public Color | Returns: the color to draw the background of selected itemsReturns the color used to draw the background of selected items. |
public Color | Returns: the color to draw the foreground of selected itemsReturns the color used to draw the foreground of selected items. |
public int | Returns: the current selection modeReturns the current selection mode for the list. |
public ListSelectionModel | Returns: theListSelectionModel that maintains the
list's selectionsReturns the current selection model. |
public String | getToolTipText(MouseEvent
the event)MouseEvent to fetch the tooltip text forOverrides javax. |
public ListUI | Returns: theListUI object that renders this componentOverrides javax. ListUI , the look and feel object that
renders this component.
|
public String | Returns: the string "ListUI"Overrides javax. "ListUI" , the UIDefaults key used to look
up the name of the javax.swing.plaf.ListUI class that defines
the look and feel for this component.
|
public boolean | Returns: the value of the selection model'sisAdjusting property.Returns the value of the selection model's |
public int | Returns: the value of thevisibleRowCount property.Returns the value of the |
public Point | Returns: the origin of the cell, ornull the cell index index)Returns the origin of the specified item in the list's coordinate system. |
public boolean | Returns: true if the specified index is selected,
else false index to be queried for selection state index)Returns |
public boolean | Returns: true if nothing is selected, else false Returns |
public int | Returns: the cell index closest to the given location, or-1 the coordinates of the point location)Returns the cell index closest to the given location in the list's coordinate system. |
protected String | Returns: aString representation of this JList .Overrides javax. String representation of this JList .
|
public void | removeListSelectionListener(ListSelectionListener
the listener)ListSelectionListener to removeRemoves a selection listener from the list. |
public void | removeSelectionInterval(int
the first index to remove from the selection index0, int the last index to remove from the selection index1)Sets the selection to be the set difference of the specified interval and the current selection. |
public void | setCellRenderer(ListCellRenderer<? super E>
the cellRenderer)ListCellRenderer
that paints list cellsSets the delegate that is used to paint each cell in the list. |
public void | setDragEnabled(boolean
whether or not to enable automatic drag handling b)Turns on or off automatic drag handling. |
pack-priv Object | Returns: any saved state for this component, ornull if nonethe drop location (as calculated by
location,dropLocationForPoint ) or null
if there's no longer a valid drop locationthe state object saved earlier for this component,
or state, boolean null whether or not the method is being called because an
actual drop occurred forDrop)Overrides javax. |
public final void | |
public void | setFixedCellHeight(int
the height to be used for all cells in the list height)Sets a fixed value to be used for the height of every cell in the list. |
public void | setFixedCellWidth(int
the width to be used for all cells in the list width)Sets a fixed value to be used for the width of every cell in the list. |
public void | setLayoutOrientation(int
the new layout orientation, one of:
layoutOrientation)VERTICAL , HORIZONTAL_WRAP or VERTICAL_WRAP Defines the way list cells are laid out. |
public void | setListData(final E[]
an array of listData)E containing the items to
display in the listConstructs a read-only |
public void | setListData(final Vector<? extends E>
a listData)Vector containing the items to
display in the listConstructs a read-only |
public void | |
public void | setPrototypeCellValue(E
the value on which to base
prototypeCellValue)fixedCellWidth and
fixedCellHeight Sets the |
public void | |
public void | setSelectedIndices(int[]
an array of the indices of the cells to select,
indices)non-null Changes the selection to be the set of indices specified by the given array. |
public void | setSelectedValue(Object
the object to select anObject, boolean true if the list should scroll to display
the selected object, if one exists; otherwise false Selects the specified object from the list. |
public void | setSelectionBackground(Color
the selectionBackground)Color to use for the
background of selected cellsSets the color used to draw the background of selected items, which cell renderers can use fill selected cells. |
public void | setSelectionForeground(Color
the selectionForeground)Color to use in the foreground
for selected list itemsSets the color used to draw the foreground of selected items, which cell renderers can use to render text and graphics. |
public void | setSelectionInterval(int
the first index to select anchor, int the last index to select lead)Selects the specified interval. |
public void | |
public void | setSelectionModel(ListSelectionModel
the selectionModel)ListSelectionModel that
implements the selectionsSets the |
public void | |
public void | setValueIsAdjusting(boolean
the new value for the property b)Sets the selection model's |
public void | setVisibleRowCount(int
an integer specifying the preferred number of
rows to display without requiring scrolling visibleRowCount)Sets the |
private void | |
public void | updateUI()
Overrides javax. ListUI property by setting it to the value provided
by the current look and feel.
|
private void | writeObject(ObjectOutputStream
the s)ObjectOutputStream in which to writeHides javax. JComponent to an
ObjectOutputStream we temporarily uninstall its UI.
|