- Type Parameters:
E
- the type of the elements of this list
- All Implemented Interfaces:
ImageObserver
,MenuContainer
,Serializable
,Accessible
,Scrollable
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 XMLEncoder
.
See How to Use Lists in The Java Tutorial for further documentation.
- Since:
- 1.2
- See Also:
ListModel
,AbstractListModel
,DefaultListModel
,ListSelectionModel
,DefaultListSelectionModel
,ListCellRenderer
,DefaultListCellRenderer
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprotected class
This class implements accessibility support for theJList
class.static class
A subclass ofTransferHandler.DropLocation
representing a drop location for aJList
.Nested classes/interfaces declared in class javax.swing.JComponent
JComponent.AccessibleJComponent
Nested classes/interfaces declared in class java.awt.Container
Container.AccessibleAWTContainer
Nested classes/interfaces declared in class java.awt.Component
Component.AccessibleAWTComponent, Component.BaselineResizeBehavior, Component.BltBufferStrategy, Component.FlipBufferStrategy
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic int
Indicates a "newspaper style" layout with cells flowing horizontally then vertically.static int
Indicates a vertical layout of cells, in a single column; the default layout.static int
Indicates a "newspaper style" layout with cells flowing vertically then horizontally.Fields declared in class javax.swing.JComponent
listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
Fields declared in class java.awt.Component
accessibleContext, BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
Fields declared in interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
-
Constructor Summary
ConstructorsConstructorDescriptionJList()
Constructs aJList
with an empty, read-only, model.Constructs aJList
that displays the elements in the specified array.Constructs aJList
that displays the elements in the specifiedVector
.Constructs aJList
that displays elements from the specified,non-null
, model. -
Method Summary
Modifier and TypeMethodDescriptionvoid
addListSelectionListener(ListSelectionListener listener)
Adds 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.void
addSelectionInterval(int anchor, int lead)
Sets the selection to be the union of the specified interval with current selection.void
Clears the selection; after calling this method,isSelectionEmpty
will returntrue
.protected ListSelectionModel
Returns an instance ofDefaultListSelectionModel
; called during construction to initialize the list's selection model property.void
ensureIndexIsVisible(int index)
Scrolls the list within an enclosing viewport to make the specified cell completely visible.protected void
fireSelectionValueChanged(int firstIndex, int lastIndex, boolean isAdjusting)
NotifiesListSelectionListener
s added directly to the list of selection changes made to the selection model.Gets theAccessibleContext
associated with thisJList
.int
Returns the anchor selection index.getCellBounds(int index0, int index1)
Returns the bounding rectangle, in the list's coordinate system, for the range of cells specified by the two indices.ListCellRenderer<? super E>
Returns the object responsible for painting list items.boolean
Returns whether or not automatic drag handling is enabled.Returns the location that this component should visually indicate as the drop location during a DnD operation over the component, ornull
if no location is to currently be shown.Returns the drop mode for this component.int
Returns the smallest list index that is currently visible.int
Returns the value of thefixedCellHeight
property.int
Returns the value of thefixedCellWidth
property.int
Returns the largest list index that is currently visible.int
Returns the layout orientation property for the list:VERTICAL
if the layout is a single column of cells,VERTICAL_WRAP
if the layout is "newspaper style" with the content flowing vertically then horizontally, orHORIZONTAL_WRAP
if the layout is "newspaper style" with the content flowing horizontally then vertically.int
Returns the lead selection index.Returns an array of all theListSelectionListener
s added to thisJList
by way ofaddListSelectionListener
.int
Returns the largest selected cell index, or-1
if the selection is empty.int
Returns the smallest selected cell index, or-1
if the selection is empty.getModel()
Returns the data model that holds the list of items displayed by theJList
component.int
getNextMatch(String prefix, int startIndex, Position.Bias bias)
Returns the next list element whosetoString
value starts with the given prefix.Computes the size of viewport needed to displayvisibleRowCount
rows.Returns the "prototypical" cell value -- a value used to calculate a fixed width and height for cells.int
getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction)
Returns the distance to scroll to expose the next or previous block.boolean
Returnstrue
if thisJList
is displayed in aJViewport
and the viewport is taller than the list's preferred height, or if the layout orientation isVERTICAL_WRAP
andvisibleRowCount <= 0
; otherwise returnsfalse
.boolean
Returnstrue
if thisJList
is displayed in aJViewport
and the viewport is wider than the list's preferred width, or if the layout orientation isHORIZONTAL_WRAP
andvisibleRowCount <= 0
; otherwise returnsfalse
.int
getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction)
Returns the distance to scroll to expose the next or previous row (for vertical scrolling) or column (for horizontal scrolling).int
Returns the smallest selected cell index; the selection when only a single item is selected in the list.int[]
Returns an array of all of the selected indices, in increasing order.Returns the value for the smallest selected cell index; the selected value when only a single item is selected in the list.Object[]
Deprecated.Returns a list of all the selected items, in increasing order based on their indices in the list.Returns the color used to draw the background of selected items.Returns the color used to draw the foreground of selected items.int
Returns the current selection mode for the list.Returns the current selection model.getToolTipText(MouseEvent event)
Returns the tooltip text to be used for the given event.getUI()
Returns theListUI
, the look and feel object that renders this component.Returns"ListUI"
, theUIDefaults
key used to look up the name of thejavax.swing.plaf.ListUI
class that defines the look and feel for this component.boolean
Returns the value of the selection model'sisAdjusting
property.int
Returns the value of thevisibleRowCount
property.indexToLocation(int index)
Returns the origin of the specified item in the list's coordinate system.boolean
isSelectedIndex(int index)
Returnstrue
if the specified index is selected, elsefalse
.boolean
Returnstrue
if nothing is selected, elsefalse
.int
locationToIndex(Point location)
Returns the cell index closest to the given location in the list's coordinate system.protected String
Returns aString
representation of thisJList
.void
removeListSelectionListener(ListSelectionListener listener)
Removes a selection listener from the list.void
removeSelectionInterval(int index0, int index1)
Sets the selection to be the set difference of the specified interval and the current selection.void
setCellRenderer(ListCellRenderer<? super E> cellRenderer)
Sets the delegate that is used to paint each cell in the list.void
setDragEnabled(boolean b)
Turns on or off automatic drag handling.void
setDropMode(DropMode dropMode)
Sets the drop mode for this component.void
setFixedCellHeight(int height)
Sets a fixed value to be used for the height of every cell in the list.void
setFixedCellWidth(int width)
Sets a fixed value to be used for the width of every cell in the list.void
setLayoutOrientation(int layoutOrientation)
Defines the way list cells are layed out.void
setListData(E[] listData)
Constructs a read-onlyListModel
from an array of items, and callssetModel
with this model.void
setListData(Vector<? extends E> listData)
Constructs a read-onlyListModel
from aVector
and callssetModel
with this model.void
Sets the model that represents the contents or "value" of the list, notifies property change listeners, and then clears the list's selection.void
setPrototypeCellValue(E prototypeCellValue)
Sets theprototypeCellValue
property, and then (if the new value isnon-null
), computes thefixedCellWidth
andfixedCellHeight
properties by requesting the cell renderer component for the given value (and index 0) from the cell renderer, and using that component's preferred size.void
setSelectedIndex(int index)
Selects a single cell.void
setSelectedIndices(int[] indices)
Changes the selection to be the set of indices specified by the given array.void
setSelectedValue(Object anObject, boolean shouldScroll)
Selects the specified object from the list.void
setSelectionBackground(Color selectionBackground)
Sets the color used to draw the background of selected items, which cell renderers can use fill selected cells.void
setSelectionForeground(Color selectionForeground)
Sets the color used to draw the foreground of selected items, which cell renderers can use to render text and graphics.void
setSelectionInterval(int anchor, int lead)
Selects the specified interval.void
setSelectionMode(int selectionMode)
Sets the selection mode for the list.void
setSelectionModel(ListSelectionModel selectionModel)
Sets theselectionModel
for the list to a non-null
ListSelectionModel
implementation.void
getSelectedValuesList()