Java Reference
In-Depth Information
TABLE 12-13 Some Constructors and Methods of the class JList (continued)
public JList(Object[] o)
//Creates a JList that displays the elements in the object
//array provided as an input parameter.
//Example: JList selectionList = new JList(o);
//
selectionList is a new list that lists the elements
//
contained in the array o.
public void setSelectionMode(ListSelectionModel listselectionmodel)
//Method to set the model for managing the list selections.
//Allows only one item to be selected or a range of
//contiguous or noncontiguous items to be selected.
//Example: pictureList.setSelectionMode
//
(ListSelectionModel.SINGLE_SELECTION);
//
limits pictureList to allow only a single selection
//
at a time.
public void setSelectionBackground(Color sbColor)
//Method to set the color of the background of a selected item
//Example: myList.setSelectionBackground(myCustomColor);
//
This statement sets the color that appears in the
//
background of a selected item in myList to the color
//
represented by the Color object myCustomColor.
public void addListSelectionListener(ListSelectionListener lsl)
//Method to add a listener class to take action when an item
//in the list is selected.
//Example: pictureList.addListSelectionListener(handler);
//
This statement adds a new ListSelectionListener object,
//
named handler, to pictureList to process the events
//
related to the selection of a list item.
public int getSelectedIndex()
//When an item in the list is selected, this method returns
//the index of that item (0 to the number of items - 1);
//returns -1 if nothing is selected
//Example: myLabel.setIcon
//
(pictures[ pictureList.getSelectedIndex() ]);
//
This statement sets an icon for a label to the item in
//
an array of image icons specified by the index of the
//
selected item in the list.
Let's write a program that uses a JList and JLabels to create the GUI as shown in
Figure 12-17.
The GUI in Figure 12-17 contains four GUI components: a JList and three JLabels .
The JList object contains the list of items, such as Pie Diagram , Line Graph , and Bar
Graph . The first JLabel contains the string "Select an Image" . Below this label is the
JList object, and below the JList object is a JLabel that displays an image. For
example, if the user selects Normal Curve, this JLabel object shows the image of a
Search WWH ::




Custom Search