Java Reference
In-Depth Information
Next, we create an array of strings consisting of the names of the images. The following
statement creates the array pictureNames of five components:
private String[] pictureNames = {"Pie Diagram",
"Line Graph",
"Bar Graph",
"Table",
"Normal Curve"};
Next, we use the array pictureNames to create the JList object pictureJList as
follows:
pictureJList = new JList(pictureNames);
As in the case of combo boxes, you can use the method setVisibleRowCount to set the
number of visible rows of a JList . For example, the following statement sets the number
of visible rows of pictureJList to 3 :
pictureJList.setVisibleRowCount(3);
In the program we are writing, we want the user to select only one item at a time
from pictureJList ,
so we set pictureJList to the single selection mode by
using
the
method
together
with
the
constant
setSelectionMode
ListSelectionModel.SINGLE_SELECTION as follows:
pictureJList.setSelectionMode
(ListSelectionModel.SINGLE_SELECTION);
When the user selects an image from pictureJList , the program displays the corre-
sponding image using the JLabel object displayPicJL . We use the class ImageIcon
and create an array of images as follows:
private ImageIcon[] pictures =
{ new ImageIcon("pieDiagram.jpg"),
new ImageIcon("lineGraph.jpg"),
new ImageIcon("barGraph.jpg"),
new ImageIcon("table.jpg"),
new ImageIcon("normalCurve.jpg")};
When the user clicks to select an item from the JList object pictureJList ,
ListSelectionEvent is generated. To process ListSelectionEvent ,weusethe
interface ListSelectionListener .This interface has the method valueChanged ,
which executes when a ListSelectionEvent occurs. The heading of this method is:
public void valueChanged(ListSelectionEvent e)
We can put the code to display the required image and its name in this method. When
the user clicks an item in the JList , we can determine the index of the selected item by
using the method getSelectedIndex . We then use this index to select the correspond-
ing image from the array pictures and the name of the image from the array
pictureNames . We can now use the method repaint to repaint the pane. The
definition of the method valueChanged is:
Search WWH ::




Custom Search