Using the JFC/Swing Packages |
AJList
presents the user with a group of items to choose from. An item can be anyObject
. Often, it's aString
. A list typically has many items, or might grow to have many items. Because most lists are placed inside of scroll panes,JList
is a scroll-savvy class.In addition to lists, the following Swing components present multiple selectable items to the user: check boxes, combo boxes, menus, radio buttons, and tables, Only check boxes, tables, and lists allow multiple items to be selected at the same time.
Here's a picture of a demo application that uses a
JList
to display the names of images to view.Below is the code from
Try this:
- Compile and run the application. The main source file is
SplitPaneDemo.java
.imagenames.properties
provides the image names to put in theJList
. You can download the entire swing lesson to get the image files used, or you can modify the properties file to use images you already have.
See Getting Started with Swing if you need help compiling or running the program.- Choose an image from the list. Use the scroll bar to see more names.
SplitPaneDemo.java
that creates and sets up the list:The code uses a...where member variables are declared this Vector is initialized from a properties file... static Vector imageList; ...where the GUI is created... // Create the list of images and put it in a scroll pane JList listOfImages = new JList(imageList); listOfImages.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); listOfImages.setSelectedIndex(0); listOfImages.addListSelectionListener(this); JScrollPane listScrollPane = new JScrollPane(listOfImages);Vector
object to provide the list with its initial items. You can also initialize a list with an array or aListModel
object.In this example, the
Vector
contains strings obtained from a properties file. However, the values in the list can be anyObject
, in which case theObject
'stoString
method provides the text to display. To display an item as an image or other non-text value, you must provide a custom cell renderer withsetCellRenderer
.By default, a list allows any combination of items to be selected at a time. You can specify a different default using the
setSelectionMode
method. For example,SplitPaneDemo
sets the selection mode toSINGLE_SELECTION
(a constant defined byListSelectionModel
) so that only one item in the list can be selected. The following table describes the three list selection modes,
Mode Description Example SINGLE_SELECTION
Once any item in the list has been selected, only one item can be selected at a time. When the user selects an item, any previously selected item is deselected first. SINGLE_INTERVAL_SELECTION
The default. Multiple, contiguous items can be selected. When the user begins a new selection, any previously selected items are deselected first. MULTIPLE_INTERVAL_SELECTION
Any combination of items can be selected. The user must explicitly deselect items. No matter which selection mode your list uses, the list fires list selection events whenever the selection changes. You can process these events by adding a list selection listener to the list with the
addListSelectionListener
method.A list selection listener must implement one method:
valueChanged
. Here's thevalueChanged
method for the listener inSplitPaneDemo
:Notice that thepublic void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting()) return; JList theList = (JList)e.getSource(); int index = theList.getSelectedIndex(); currentImage = new ImageIcon("images/" + (String)imageList.elementAt(index)); picture.setIcon(currentImage); picture.setPreferredSize(new Dimension(currentImage.getIconWidth(), currentImage.getIconHeight() )); picture.revalidate(); }valueChanged
method updates the image only ifgetValueIsAdjusting
returnsfalse
. Many list selection events can be generated from a single user action such as a mouse click. This particular program is interested only in the final result of the user's action.Because the list is in single selection mode, this code can use
getSelectedIndex
to get the index of the just-selected item.JList
provides other methods for setting or getting the selection when the selection mode allows more than one item to be selected. For an example that let's you change the selection mode of a list dynamically, see Examples of Handling List Selection Events.The List API
The following tables list the commonly usedJList
constructors and methods. Other methods you're likely to call are defined by theJComponent
andComponent
classes and include [PENDING: anything in particular for JList?]. [Link to JComponent and Component discussions.]Much of the operation of a list is managed by other objects. For example, the items in the list are managed by a list model object, the selection is managed by a list selection model object, and most programs put a list in a scroll pane to handle scrolling. For the most part, you don't need to worry about these helper objects because
JList
creates them as necessary and you interact with them implicitly withJList
's convenience methods.That said, the API for using lists falls into three categories:
Setting the Items in the List Method Purpose JList(ListModel)
JList(Object[])
JList(Vector)Create a list with the initial list items specified. The second and third constructors implicitly create a ListModel
.void setModel(ListModel)
ListModel getModel()Set or get the model that contains the contents of the list. You can dynamically modify the contents of the list by calling methods on the object returned by getModel
.void setListData(Object[])
void setListData(Vector)Set the items in the list. These methods implicitly create a ListModel
.
Managing the List's Selection Method Purpose void setSelectedIndex(int)
void setSelectedIndices(int[])
void setSelectedValue(Object, boolean)
void setSelectedInterval(int, int)Set the current selection as indicated. Note that JList
supports multiple selection although by default multiple selection is turned off. UsesetSelectionMode
to set either single or multiple selection. The boolean argument specifies whether the list should attempt to scroll itself so that the selected item is visible.int getSelectedIndex()
int getMinSelectionIndex()
int getMaxSelectionIndex()
int[] getSelectedIndices()
Object getSelectedValue()
Object[] getSelectedValues()Get information about the current selection as indicated. void setSelectionMode(int)
int getSelectionMode()Set or get the selection mode. Acceptable values are: SINGLE_SELECTION
,SINGLE_INTERVAL_SELECTION
, orMULTIPLE_INTERVAL_SELECTION
.void clearSelection()
boolean isSelectionEmpty()Set or get whether any items are selected. boolean isSelectedIndex(int)
Determine whether the specified index is selected.
Working with a Scroll Pane Method Purpose void ensureIndexIsVisible(int)
Scroll so that the specified index is visible within the viewport that this list is in. int getFirstVisibleIndex()
int getLastVisibleIndex()Get the index of the first or last visible item. void setVisibleRowCount(int)
int getVisibleRowCount()Set or get how many rows of the list are visible. Examples that Use Lists
This table shows the examples that useJList
and where those examples are described.
Example Where Described Notes SplitPaneDemo.java
This page and
How to Use Split PanesContains a single selection list. ListSelectionDemo.java
How to Write a List Selection Listener Contains a list and a table that share the same selection model. You can dynamically choose the selection mode. SharedModelDemo.java
Nowhere yet Modifies ListSelectionDemo so that the list and table share the same data model.
Using the JFC/Swing Packages |