CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Layout

Controls and layout managers
Components
Lists

A frame that includes a list

Common constructors of the JList class

Constructor Description
JList(Object[]) Creates a list that contains the objects stored in the specified array of objects.
JList(ListModel) Creates a list using the specified list model.

Some methods of the JList class

Method Description
getSelectedValue() Returns the selected item as an Object type.
getSelectedIndex() Returns an int value for the index of the selected item.
isSelectedIndex(intIndex) Returns a true value if the item at the specified index is selected.
setFixedCellWidth(intPixels) Sets the cell width to the specified number of pixels. Otherwise, the width of the list is slightly wider than the widest item in the array that populates the list.
setVisibleRowCount(intRows) Sets the visible row count to the specified int value. This only works when the list is displayed within a scroll pane.
setSelectionMode(mode) Sets the selection mode. To allow single selections, specify ListSelectionModel.SINGLE_SELECTION.
setSelectedIndex(intIndex) Selects the item at the specified index.

Code that creates a list

descriptions = getProductDescriptions(); // returns an array of descriptions
productList = new JList(descriptions);
productList.setFixedCellWidth(200);
productList.setVisibleRowCount(5);
productList.setSelectedIndex(0);
productList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
add(new JScrollPane(productList));

Code that gets the selected item

String s = (String)productList.getSelectedValue();
Previous | Summary | Text areas | Scroll panes | Check boxes | Radio buttons | Borders | Combo boxes | Event listeners | Lists | Multiple selections in a list | List models | Next