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:
// This list model has about 2^16 elements. Enjoy scrolling.
ListModel bigData = new AbstractListModel() {
public int getSize() { return Short.MAX_VALUE; }
public Object getElementAt(int index) { return "Index " + index; }
};
JList bigDataList = new JList(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 uses a java.awt.Component, provided by a delegate called the cellRendererer, to paint the visible cells in the list. The cell renderer component is used like a "rubber stamp" to paint each visible row. Each time the JList needs to paint a cell it asks the cell renderer for the component, moves it into place using setBounds() and then draws it by calling its paint method. The default cell renderer uses a JLabel component to render the string value of each component. You can substitute your own cell renderer, using code like this:
// Display an icon and a string for each object in the list.
class MyCellRenderer extends JLabel implements ListCellRenderer {
final static ImageIcon longIcon = new ImageIcon("long.gif");
final static 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,
Object value, // value to display
int index, // cell index
boolean isSelected, // is the cell selected
boolean cellHasFocus) // the list and the cell have the 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;
}
}
String[] data = {"one", "two", "three", "four"};
JList dataList = new JList(data);
dataList.setCellRenderer(new MyCellRenderer());
JList doesn't provide any special support for handling double or triple (or N) mouse clicks however it's easy to handle them using a MouseListener. Use the JList method locationToIndex() to determine what cell was clicked. For example:
final JList list = new JList(dataModel);
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);
Note that in this example the dataList is final because it's referred to by the anonymous MouseListener class. For the keyboard keys used by this component in the standard look and feel (L&F) renditions, see the JList key assignments.
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 JavaBeansTM has been added to the java.beans package. Please see java.beans.XMLEncoder.
See How to Use Lists in The Java Tutorial for further documentation. Also see the article Advanced JList Programming in The Swing Connection.
| Field Detail |
private static final java.lang.String uiClassID
public static final int VERTICAL
public static final int VERTICAL_WRAP
public static final int HORIZONTAL_WRAP
private int layoutOrientation
VERTICAL.| Constructor Detail |
public JList(javax.swing.ListModel dataModel)
JList that displays the elements in the specified, non-null model. All JList constructors delegate to this one.dataModel - the data model for this listIllegalArgumentException - if dataModel is nullpublic JList(java.lang.Object[] listData)
JList that displays the elements in the specified array. This constructor just delegates to the ListModel constructor.listData - the array of Objects to be loaded into the data modelpublic JList(java.util.Vector listData)
JList that displays the elements in the specified Vector. This constructor just delegates to the ListModel constructor.listData - the Vector to be loaded into the data modelpublic JList()
JList with an empty model.| Method Detail |
public javax.swing.plaf.ListUI getUI()
ListUI object that renders this componentpublic void setUI(javax.swing.plaf.ListUI ui)
ui - the ListUI L&F objectpublic void updateUI()
public java.lang.String getUIClassID()
public java.lang.Object getPrototypeCellValue()
prototypeCellValue propertypublic void setPrototypeCellValue(java.lang.Object prototypeCellValue)
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.
prototypeCellValue - the value on which to base fixedCellWidth and fixedCellHeightpublic int getFixedCellWidth()
fixedCellWidth property, rather than that calculated from the list elements.public void setFixedCellWidth(int width)
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.
width - the width, in pixels, for all cells in this listpublic int getFixedCellHeight()
fixedCellHeight property, rather than that calculated from the list elements.public void setFixedCellHeight(int height)
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.
height - an integer giving the height, in pixels, for all cells in this listpublic javax.swing.ListCellRenderer getCellRenderer()
ListCellRendererpublic void setCellRenderer(javax.swing.ListCellRenderer cellRenderer)
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.
cellRenderer - the ListCellRenderer that paints list cellspublic java.awt.Color getSelectionForeground()
Color object for the foreground propertypublic void setSelectionForeground(java.awt.Color selectionForeground)
The default value of this property is defined by the look and feel implementation.
This is a JavaBeans bound property.
selectionForeground - the Color to use in the foreground for selected list itemspublic java.awt.Color getSelectionBackground()
Color used for the background of selected list itemspublic void setSelectionBackground(java.awt.Color selectionBackground)
The default value of this property is defined by the look and feel implementation.
This is a JavaBeans bound property.
selectionBackground - the Color to use for the background of selected cellspublic int getVisibleRowCount()
public void setVisibleRowCount(int visibleRowCount)
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.
visibleRowCount - an integer specifying the preferred number of visible rowspublic int getLayoutOrientation()
JList.VERTICAL if the layout is a single column of cells, or JList.VERTICAL_WRAP if the layout is "newspaper style" with the content flowing vertically then horizontally or JList.HORIZONTAL_WRAP if the layout is "newspaper style" with the content flowing horizontally then vertically.public void setLayoutOrientation(int layoutOrientation)
JList with four cells, this can be layed out in one of the following ways: 0 1 2 3
0 1 2 3
0 2 1 3
These correspond to the following values:
JList.VERTICAL | The cells should be layed out vertically in one column. |
JList.HORIZONTAL_WRAP | The cells should be layed out horizontally, wrapping to a new row as necessary. The number of rows to use will either be defined by getVisibleRowCount if > 0, otherwise the number of rows will be determined by the width of the JList. |
JList.VERTICAL_WRAP | The cells should be layed out vertically, wrapping to a new column as necessary. The number of rows to use will either be defined by getVisibleRowCount if > 0, otherwise the number of rows will be determined by the height of the JList. |
JList.VERTICAL. This will throw an IllegalArgumentException if layoutOrientation is not one of JList.HORIZONTAL_WRAP or JList.VERTICAL or JList.VERTICAL_WRAP
layoutOrientation - New orientation, one of JList.HORIZONTAL_WRAP, JList.VERTICAL or JList.VERTICAL_WRAP.public int getFirstVisibleIndex()
componentOrientation property. If the orientation is horizontal left-to-right, then the first visible cell is in the list's upper-left corner. If the orientation is horizontal right-to-left, then the first visible cell is in the list's upper-right corner. If nothing is visible or the list is empty, a -1 is returned. Note that the returned cell may only be partially visible.public int getLastVisibleIndex()
componentOrientation property. If the orientation is horizontal left-to-right, then the last visible cell is in the JList's lower-right corner. If the orientation is horizontal right-to-left, then the last visible cell is in the JList's lower-left corner. If nothing is visible or the list is empty, a -1 is returned. Note that the returned cell may only be partially visible.public void ensureIndexIsVisible(int index)
JList must be displayed within a JViewport.index - the index of the cell to make visiblepublic void setDragEnabled(boolean b)
dragEnabled property, which must be true to enable automatic drag handling (the first part of drag and drop) on this component. The transferHandler property needs to be set to a non-null value for the drag to do anything. The default value of the dragEnabled property is false. When automatic drag handling is enabled, most look and feels begin a drag-and-drop operation whenever the user presses the mouse button over a selection and then moves the mouse a few pixels. Setting this property to true can therefore have a subtle effect on how selections behave.
Some look and feels might not support automatic drag and drop; they will ignore this property. You can work around such look and feels by modifying the component to directly call the exportAsDrag method of a TransferHandler.
b - the value to set the dragEnabled property toHeadlessException - if b is true and GraphicsEnvironment.isHeadless() returns truepublic boolean getDragEnabled()
dragEnabled property.dragEnabled property
public int getNextMatch(java.lang.String prefix,
int startIndex,
Position.Bias bias)
prefix - the string to test for a matchstartIndex - the index for starting the searchbias - the search direction, either Position.Bias.Forward or Position.Bias.Backward.IllegalArgumentException - if prefix is null or startIndex is out of boundspublic java.lang.String getToolTipText(java.awt.event.MouseEvent event)
JComponent's getToolTipText method in order to allow the renderer's tips to be used if it has text set. JList to properly display tooltips of its renderers JList must be a registered component with the ToolTipManager. This is done automatically in the constructor, but if at a later point JList is told setToolTipText(null) it will unregister the list component, and no tips from renderers will display anymore.
public int locationToIndex(java.awt.Point location)
JList coordinates to the closest index of the cell at that location. To determine if the cell actually contains the specified location use a combination of this method and getCellBounds. Returns -1 if the model is empty.location - the coordinates of the cell, relative to JListpublic java.awt.Point indexToLocation(int index)
JList coordinates. Returns null if index isn't valid.index - the index of the JList cell
public java.awt.Rectangle getCellBounds(int index0,
int index1)
JList coordinates. Returns null if index isn't valid.index0 - the index of the first JList cell in the rangeindex1 - the index of the last JList cell in the rangepublic javax.swing.ListModel getModel()
JList component.ListModel that provides the displayed list of itemspublic void setModel(javax.swing.ListModel model)
PropertyChangeListeners. This is a JavaBeans bound property.
model - the ListModel that provides the list of items for displayIllegalArgumentException - if model is nullpublic void setListData(java.lang.Object[] listData)
ListModel from an array of objects and then applies setModel to it.listData - an array of Objects containing the items to display in the listpublic void setListData(java.util.Vector listData)
ListModel from a Vector and then applies setModel to it.listData - a Vector containing the items to display in the listprotected javax.swing.ListSelectionModel createSelectionModel()
DefaultListSelectionModel. This method is used by the constructor to initialize the selectionModel property.ListSelectionModel used by this JList.public javax.swing.ListSelectionModel getSelectionModel()
ListSelectionModel that implements list selections
protected void fireSelectionValueChanged(int firstIndex,
int lastIndex,
boolean isAdjusting)
JList ListSelectionListeners that the selection model has changed. It's used to forward ListSelectionEvents from the selectionModel to the ListSelectionListeners added directly to the JList.firstIndex - the first selected indexlastIndex - the last selected indexisAdjusting - true if multiple changes are being madepublic void addListSelectionListener(javax.swing.event.ListSelectionListener listener)
JList will have their ListSelectionEvent.getSource() == this JList (instead of the ListSelectionModel).listener - the ListSelectionListener to addpublic void removeListSelectionListener(javax.swing.event.ListSelectionListener listener)
listener - the ListSelectionListener to removepublic javax.swing.event.ListSelectionListener[] getListSelectionListeners()
ListSelectionListeners added to this JList with addListSelectionListener().ListSelectionListeners added or an empty array if no listeners have been addedpublic void setSelectionModel(javax.swing.ListSelectionModel selectionModel)
selectionModel for the list to a non-null ListSelectionModel 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.
selectionModel - the ListSelectionModel that implements the selectionsIllegalArgumentException - if selectionModel is nullpublic void setSelectionMode(int selectionMode)
selectionMode values are allowed: ListSelectionModel.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. ListSelectionModel.SINGLE_INTERVAL_SELECTION One contiguous index interval can be selected at a time. In this mode setSelectionInterval and addSelectionInterval are equivalent. ListSelectionModel.MULTIPLE_INTERVAL_SELECTION In this mode, there's no restriction on what can be selected. This is the default. selectionMode - an integer specifying the type of selections that are permissiblepublic int getSelectionMode()
selectionMode propertypublic int getAnchorSelectionIndex()
addSelectionModel or setSelectionInterval call. This is a convenience method that just delegates to the selectionModel.public int getLeadSelectionIndex()
addSelectionInterval or setSelectionInterval call. This is a convenience method that just delegates to the selectionModel.public int getMinSelectionIndex()
selectionModel.public int getMaxSelectionIndex()
selectionModel.public boolean isSelectedIndex(int index)
selectionModel.index - index to be queried for selection statepublic boolean isSelectionEmpty()
selectionModel.public void clearSelection()
isSelectionEmpty will return true. This is a convenience method that just delegates to the selectionModel.
public void setSelectionInterval(int anchor,
int lead)
anchor and lead indices are included. It's not necessary for anchor to be less than lead. This is a convenience method that just delegates to the selectionModel. The DefaultListSelectionModel implementation will do nothing if either anchor or lead are -1. If anchor or lead are less than -1, IndexOutOfBoundsException is thrown.anchor - the first index to selectlead - the last index to selectIndexOutOfBoundsException - if either anchor or lead are less than -1
public void addSelectionInterval(int anchor,
int lead)
selectionModel. The DefaultListSelectionModel implementation will do nothing if either anchor or lead are -1. If anchor or lead are less than -1, IndexOutOfBoundsException is thrown.anchor - the first index to add to the selectionlead - the last index to add to the selectionIndexOutOfBoundsException - if either anchor or lead are less than -1
public void removeSelectionInterval(int index0,
int index1)
index0 and index1 indices are removed. It's not necessary for index0 to be less than index1. This is a convenience method that just delegates to the selectionModel. The DefaultListSelectionModel implementation will do nothing if either index0 or index1 are -1. If index0 or index1 are less than -1, IndexOutOfBoundsException is thrown.index0 - the first index to remove from the selectionindex1 - the last index to remove from the selectionIndexOutOfBoundsException - if either index0 or index1 are less than -1public void setValueIsAdjusting(boolean b)
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).b - the boolean value for the property valuepublic boolean getValueIsAdjusting()
isAdjusting property. This value is true if multiple changes are being made.public int[] getSelectedIndices()
public void setSelectedIndex(int index)
index - the index of the one cell to selectpublic void setSelectedIndices(int[] indices)
indices - an array of the indices of the cells to selectpublic java.lang.Object[] getSelectedValues()
public int getSelectedIndex()
getMinSelectionIndexpublic java.lang.Object getSelectedValue()
null if the selection is empty.
public void setSelectedValue(java.lang.Object anObject,
boolean shouldScroll)
anObject - the object to selectshouldScroll - true if the list should scroll to display the selected object, if one exists; otherwise false
private void checkScrollableParameters(java.awt.Rectangle visibleRect,
int orientation)
public java.awt.Dimension getPreferredScrollableViewportSize()
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: visibleRowCount. 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. VERTICAL, than this will return the value from getPreferredSize. The current ListUI is expected to override getPreferredSize to return an appropriate value.visibleRowCount rows
public int getScrollableUnitIncrement(java.awt.Rectangle visibleRect,
int orientation,
int direction)
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().
visibleRect - the visible rectangleorientation - HORIZONTAL or VERTICALdirection - if <= 0, then scroll UP; if > 0, then scroll DOWNIllegalArgumentException - if visibleRect is null, or orientation isn't one of SwingConstants.VERTICAL, SwingConstants.HORIZONTAL.
public int getScrollableBlockIncrement(java.awt.Rectangle visibleRect,
int orientation,
int direction)
direction is greater than 0), the last visible element should become the first completely visible element For horizontal scrolling if the list is layed out horizontally (the orientation is VERTICAL_WRAP or HORIZONTAL_WRAP):
direction is greater than 0), the next column should become the first visible column Note that the value of visibleRect must be the equal to this.getVisibleRect().
visibleRect - the visible rectangleorientation - HORIZONTAL or VERTICALdirection - if <= 0, then scroll UP; if > 0, then scroll DOWNIllegalArgumentException - if visibleRect is null, or orientation isn't one of SwingConstants.VERTICAL, SwingConstants.HORIZONTAL.public boolean getScrollableTracksViewportWidth()
JList is displayed in a JViewport and the viewport is wider than JList's preferred width; or if the layout orientation is HORIZONTAL_WRAP and the visible row count is <= 0; 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.JList's preferred width, otherwise falsepublic boolean getScrollableTracksViewportHeight()
JList is displayed in a JViewport and the viewport is taller than JList's preferred height, or if the layout orientation is VERTICAL_WRAP and the number of visible rows is <= 0;
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.Jlist's preferred height, otherwise falseprotected java.lang.String paramString()
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.JList.public javax.accessibility.AccessibleContext getAccessibleContext()