Java Reference
In-Depth Information
public void valueChanged(ListSelectionEvent e)
{
displayPicJL.setIcon(
pictures[pictureJList.getSelectedIndex()]);
infoJL.setText(
pictureNames[pictureJList.getSelectedIndex()]);
repaint();
}
Of course, we must register the list selection listener to the JList . The following
statement accomplishes this:
pictureJList.addListSelectionListener( this );
There are five items in pictureJList . When the program executes, it displays only
three of these items in the list at a time. Therefore, we want to attach a vertical scroll bar
to pictureJList , so that the user can scroll to select an item not currently shown in the
list. To do so, we use the class JScrollPane as follows. First, we create the
JScrollPane object selectionJS and initialize this object using the object
pictureJList . We then add the object to the pane selectionJS . The following
statements illustrate this concept:
selectionJS = new JScrollPane(pictureJList);
pane.add(selectionJS);
We will set the pane layout to null and specify the size and location of the GUI
components. The complete program listing contains the following statements:
//Program to demonstrate JLIST
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
public class JListPictureViewer extends JFrame implements
ListSelectionListener
{
private String[] pictureNames = {"Pie Diagram",
"Line Graph",
"Bar Graph",
"Table",
"Normal Curve"};
1
2
private ImageIcon[] pictures =
{ new ImageIcon("pieDiagram.jpg"),
new ImageIcon("lineGraph.jpg"),
new ImageIcon("barGraph.jpg"),
new ImageIcon("table.jpg"),
new ImageIcon("normalCurve.jpg")};
Search WWH ::




Custom Search