javax.swing

Class JList

Implemented Interfaces:
Accessible, ImageObserver, MenuContainer, Scrollable, Serializable

public class JList
extends JComponent
implements Accessible, Scrollable

This class is a facade over three separate objects: ListModel, ListSelectionModel and ListUI. The facade represents a unified "list" concept, with independently replacable (possibly client-provided) models for its contents and its current selection. In addition, each element in the list is rendered via a strategy class ListCellRenderer.

Lists have many properties, some of which are stored in this class while others are delegated to the list's model or selection. The following properties are available:

Property Stored inBound?
accessibleContext list no
anchorSelectionIndex selectionno
cellRenderer list yes
dragEnabled list no
firstVisibleIndex list no
fixedCellHeight list yes
fixedCellWidth list yes
lastVisibleIndex list no
layoutOrientation list yes
leadSelectionIndex selectionno
maxSelectionIndex selectionno
minSelectionIndex selectionno
model list yes
opaque list no
preferredScrollableViewportSizelist no
prototypeCellValue list yes
scrollableTracksViewportHeight list no
scrollableTracksViewportWidth list no
selectedIndex selectionno
selectedIndices selectionno
selectedValue model no
selectedValues model no
selectionBackground list yes
selectionEmpty selectionno
selectionForeground list yes
selectionMode selectionno
selectionModel list yes
UI list yes
UIClassID list no
valueIsAdjusting list no
visibleRowCount list no
See Also:
Serialized Form

Nested Class Summary

protected class
JList.AccessibleJList
Provides accessibility support for JList.

Nested classes/interfaces inherited from class javax.swing.JComponent

JComponent.AccessibleJComponent

Nested classes/interfaces inherited from class java.awt.Container

Container.AccessibleAWTContainer

Nested classes/interfaces inherited from class java.awt.Component

Component.AccessibleAWTComponent, Component.BltBufferStrategy, Component.FlipBufferStrategy

Field Summary

static int
HORIZONTAL_WRAP
Constant value used in "layoutOrientation" property.
static int
VERTICAL
Constant value used in "layoutOrientation" property.
static int
VERTICAL_WRAP
Constant value used in "layoutOrientation" property.

Fields inherited from class javax.swing.JComponent

TOOL_TIP_TEXT_KEY, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW, accessibleContext, listenerList, ui

Fields inherited from class java.awt.Component

BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

Fields inherited from interface java.awt.image.ImageObserver

ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

Constructor Summary

JList()
Creates a new JList object.
JList(Vector items)
Creates a new JList object.
JList(Object[] items)
Creates a new JList object.
JList(ListModel model)
Creates a new JList object.

Method Summary

void
addListSelectionListener(ListSelectionListener listener)
Adds a ListSelectionListener to the listener list for this list.
void
addSelectionInterval(int anchor, int lead)
Adds the specified interval to the current selection.
void
clearSelection()
Clears the current selection.
protected ListSelectionModel
createSelectionModel()
Creates the default ListSelectionModel.
void
ensureIndexIsVisible(int i)
Scrolls this list to make the specified cell visible.
protected void
fireSelectionValueChanged(int firstIndex, int lastIndex, boolean isAdjusting)
Fire a ListSelectionEvent to all the registered ListSelectionListeners.
AccessibleContext
getAccessibleContext()
If a component supports the Accessibility API then this method should not return null.
int
getAnchorSelectionIndex()
Returns the index of the anchor item in the current selection, or -1 if there is no anchor item.
Rectangle
getCellBounds(int index0, int index1)
Returns the bounds of the rectangle that encloses both list cells with index0 and index1.
ListCellRenderer
getCellRenderer()
Gets the value of the cellRenderer property.
boolean
getDragEnabled()
Return the value of the dragEnabled property.
int
getFirstVisibleIndex()
Returns the list index of the upper left or upper right corner of the visible rectangle of this list, depending on the Component.getComponentOrientation() property.
int
getFixedCellHeight()
Gets the value of the fixedCellHeight property.
int
getFixedCellWidth()
Gets the value of the fixedCellWidth property.
int
getLastVisibleIndex()
Returns the list index of the lower right or lower left corner of the visible rectangle of this list, depending on the Component.getComponentOrientation() property.
int
getLayoutOrientation()
Returns the layout orientation, which will be one of VERTICAL, VERTICAL_WRAP and HORIZONTAL_WRAP.
int
getLeadSelectionIndex()
Returns the index of the lead item in the current selection, or -1 if there is no lead item.
ListSelectionListener[]
getListSelectionListeners()
Returns an array of all ListSelectionListeners subscribed to this list.
int
getMaxSelectionIndex()
Returns the highest item index in the current selection, or -1 if there is no selection.
int
getMinSelectionIndex()
Returns the lowest item index in the current selection, or -1 if there is no selection.
ListModel
getModel()
Gets the value of the model property.
int
getNextMatch(String prefix, int startIndex, Position.Bias direction)
Returns the index of the next list element (beginning at startIndex and moving in the specified direction through the list, looping around if necessary) that starts with prefix (ignoring case).
Dimension
getPreferredScrollableViewportSize()
Returns a size indicating how much space this list would like to consume, when contained in a scrollable viewport.
Object
getPrototypeCellValue()
Returns the current value of the prototypeCellValue property.
int
getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction)
Return the number of pixels the list must scroll in order to move a "block" of the list into the provided visible rectangle.
boolean
getScrollableTracksViewportHeight()
Gets the value of the scrollableTracksViewportWidth property.
boolean
getScrollableTracksViewportWidth()
Gets the value of the scrollableTracksViewportWidth property.
int
getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction)
Return the number of pixels the list must scroll in order to move a "unit" of the list into the provided visible rectangle.
int
getSelectedIndex()
Returns the minimum index of an element in the list which is currently selected.
int[]
getSelectedIndices()
Returns the indices of values in the model property which are selected.
Object
getSelectedValue()
Returns the first value in the list's model property which is selected, according to the list's selectionModel property.
Object[]
getSelectedValues()
Returns all the values in the list's model property which are selected, according to the list's selectionModel property.
Color
getSelectionBackground()
Gets the value of the selectionBackground property.
Color
getSelectionForeground()
Gets the value of the selectionForeground property.
int
getSelectionMode()
Returns the selection mode for the list (one of: ListSelectionModel.SINGLE_SELECTION, ListSelectionModel.SINGLE_INTERVAL_SELECTION and ListSelectionModel.MULTIPLE_INTERVAL_SELECTION).
ListSelectionModel
getSelectionModel()
Returns the selection model for the JList component.
ListUI
getUI()
Gets the value of the UI property.
String
getUIClassID()
Return the class identifier for the list's UI property.
boolean
getValueIsAdjusting()
Returns the valueIsAdjusting flag from the list's selection model.
int
getVisibleRowCount()
Gets the value of the visibleRowCount property.
Point
indexToLocation(int index)
Returns location of the cell located at the specified index in the list.
boolean
isSelectedIndex(int a)
Indicates whether the list element at a given index value is currently selected.
boolean
isSelectionEmpty()
Returns true if the model's selection is empty, otherwise false.
int
locationToIndex(Point location)
Returns index of the cell to which specified location is closest to.
protected String
paramString()
Returns a string describing the attributes for the JList component, for use in debugging.
void
removeListSelectionListener(ListSelectionListener listener)
Removes a ListSelectionListener from the listener list for this list.
void
removeSelectionInterval(int index0, int index1)
Removes the specified interval from the current selection.
void
setCellRenderer(ListCellRenderer renderer)
Sets the value of the getCellRenderer() property.
void
setDragEnabled(boolean enabled)
Set the dragEnabled property.
void
setFixedCellHeight(int h)
Sets the value of the fixedCellHeight property.
void
setFixedCellWidth(int w)
Sets the value of the fixedCellWidth property.
void
setLayoutOrientation(int orientation)
Sets the layout orientation (this is a bound property with the name 'layoutOrientation').
void
setListData(Vector listData)
Sets the model property of the list to a new anonymous AbstractListModel subclass which accesses the provided vector directly.
void
setListData(Object[] listData)
Sets the model property of the list to a new anonymous AbstractListModel subclass which accesses the provided Object array directly.
void
setModel(ListModel model)
Sets the value of the model property.
void
setPrototypeCellValue(Object obj)
Set the prototypeCellValue property.
void
setSelectedIndex(int a)
Adds the interval [a,a] to the set of selections managed by this list's selectionModel property.
void
setSelectedIndices(int[] a)
For each element a[i] of the provided array a, calls setSelectedIndex(int) on a[i].
void
setSelectedValue(Object obj, boolean scroll)
Sets the selection to cover only the specified value, if it exists in the model.
void
setSelectionBackground(Color c)
Sets the value of the selectionBackground property.
void
setSelectionForeground(Color c)
Sets the value of the selectionForeground property.
void
setSelectionInterval(int anchor, int lead)
Sets the current selection to the items in the specified range (inclusive).
void
setSelectionMode(int a)
Sets the list's "selectionMode" property, which simply mirrors the same property on the list's selectionModel property.
void
setSelectionModel(ListSelectionModel model)
Sets the value of the selectionModel property.
void
setUI(ListUI ui)
Sets the value of the UI property.
void
setValueIsAdjusting(boolean isAdjusting)
Sets the valueIsAdjusting flag in the list's selection model.
void
setVisibleRowCount(int vc)
Sets the value of the visibleRowCount property.
void
updateUI()
Calls setUI(ListUI) with the ListUI subclass returned from calling UIManager.getUI(JComponent).

Methods inherited from class javax.swing.JComponent

addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, extends EventListener> T[] getListeners, firePropertyChange, firePropertyChange, fireVetoableChange, getAccessibleContext, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getUIClassID, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, paramString, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setNextFocusableComponent, setOpaque, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update, updateUI

Methods inherited from class java.awt.Container

add, add, add, add, add, addContainerListener, addImpl, addNotify, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, extends EventListener> T[] getListeners, findComponentAt, findComponentAt, getAlignmentX, getAlignmentY, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponentZOrder, getComponents, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getInsets, getLayout, getMaximumSize, getMinimumSize, getPreferredSize, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paint, paintComponents, paramString, preferredSize, print, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, removeNotify, setComponentZOrder, setFocusCycleRoot, setFocusTraversalKeys, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setFont, setLayout, transferFocusDownCycle, update, validate, validateTree

Methods inherited from class java.awt.Component

action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, addNotify, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, bounds, checkImage, checkImage, coalesceEvents, contains, contains, createImage, createImage, createVolatileImage, createVolatileImage, deliverEvent, disable, disableEvents, dispatchEvent, doLayout, enable, enable, enableEvents, enableInputMethods, extends EventListener> T[] getListeners, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getAccessibleContext, getAlignmentX, getAlignmentY, getBackground, getBounds, getBounds, getColorModel, getComponentAt, getComponentAt, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeys, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getGraphics, getGraphicsConfiguration, getHeight, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocation, getLocationOnScreen, getMaximumSize, getMinimumSize, getMouseListeners, getMouseMotionListeners, getMouseWheelListeners, getName, getParent, getPeer, getPreferredSize, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getSize, getToolkit, getTreeLock, getWidth, getX, getY, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, invalidate, isBackgroundSet, isCursorSet, isDisplayable, isDoubleBuffered, isEnabled, isFocusCycleRoot, isFocusOwner, isFocusTraversable, isFocusable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, layout, list, list, list, list, list, locate, location, lostFocus, minimumSize, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paint, paintAll, paramString, postEvent, preferredSize, prepareImage, prepareImage, print, printAll, processComponentEvent, processEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removeNotify, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, reshape, resize, resize, setBackground, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setEnabled, setFocusTraversalKeys, setFocusTraversalKeysEnabled, setFocusable, setFont, setForeground, setIgnoreRepaint, setLocale, setLocation, setLocation, setMaximumSize, setMinimumSize, setName, setPreferredSize, setSize, setSize, setVisible, show, show, size, toString, transferFocus, transferFocusBackward, transferFocusUpCycle, update, validate

Methods inherited from class java.lang.Object

clone, equals, extends Object> getClass, finalize, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Details

HORIZONTAL_WRAP

public static final int HORIZONTAL_WRAP
Constant value used in "layoutOrientation" property. This value means that cells are laid out in multiple columns "newspaper style", filling horizontally first, then vertically.
Field Value:
2

VERTICAL

public static final int VERTICAL
Constant value used in "layoutOrientation" property. This value means that cells are laid out in a single vertical column. This is the default.
Field Value:
0

VERTICAL_WRAP

public static final int VERTICAL_WRAP
Constant value used in "layoutOrientation" property. This value means that cells are laid out in multiple columns "newspaper style", filling vertically first, then horizontally.
Field Value:
1

Constructor Details

JList

public JList()
Creates a new JList object.

JList

public JList(Vector items)
Creates a new JList object.
Parameters:
items - the initial list items.

JList

public JList(Object[] items)
Creates a new JList object.
Parameters:
items - the initial list items.

JList

public JList(ListModel model)
Creates a new JList object.
Parameters:
model - a model containing the list items (null not permitted).
Throws:
IllegalArgumentException - if model is null.

Method Details

addListSelectionListener

public void addListSelectionListener(ListSelectionListener listener)
Adds a ListSelectionListener to the listener list for this list. The listener will be called back with a ListSelectionEvent any time the list's selectionModel property changes. The source of such events will be the JList, not the selection model.
Parameters:
listener - The new listener to add

addSelectionInterval

public void addSelectionInterval(int anchor,
                                 int lead)
Adds the specified interval to the current selection. Note that anchor can be less than, equal to, or greater than lead.
Parameters:
anchor - the index of the anchor item.
lead - the index of the lead item.

clearSelection

public void clearSelection()
Clears the current selection.

createSelectionModel

protected ListSelectionModel createSelectionModel()
Creates the default ListSelectionModel.
Returns:
the ListSelectionModel

ensureIndexIsVisible

public void ensureIndexIsVisible(int i)
Scrolls this list to make the specified cell visible. This only works if the list is contained within a viewport.
Parameters:
i - The list index to make visible

fireSelectionValueChanged

protected void fireSelectionValueChanged(int firstIndex,
                                         int lastIndex,
                                         boolean isAdjusting)
Fire a ListSelectionEvent to all the registered ListSelectionListeners.
Parameters:
firstIndex - the lowest index covering the selection change.
lastIndex - the highest index covering the selection change.
isAdjusting - a flag indicating if this event is one in a series of events updating the selection.

getAccessibleContext

public AccessibleContext getAccessibleContext()
If a component supports the Accessibility API then this method should not return null. Only classes which must extend an accessible class, but must not itself be accessible, may return null.
Specified by:
getAccessibleContext in interface Accessible
Overrides:
getAccessibleContext in interface JComponent
Returns:
the context associated with this accessible object

getAnchorSelectionIndex

public int getAnchorSelectionIndex()
Returns the index of the anchor item in the current selection, or -1 if there is no anchor item.
Returns:
The item index.

getCellBounds

public Rectangle getCellBounds(int index0,
                               int index1)
Returns the bounds of the rectangle that encloses both list cells with index0 and index1.
Parameters:
index0 - the index of the first cell
index1 - the index of the second cell
Returns:
the bounds of the rectangle that encloses both list cells with index0 and index1, null if one of the indices is not valid

getCellRenderer

public ListCellRenderer getCellRenderer()
Gets the value of the cellRenderer property.
Returns:
The current value of the property

getDragEnabled

public boolean getDragEnabled()
Return the value of the dragEnabled property.
Returns:
the value
Since:
1.4

getFirstVisibleIndex

public int getFirstVisibleIndex()
Returns the list index of the upper left or upper right corner of the visible rectangle of this list, depending on the