Components allows us to interact with the application. A layout manager class is responsible for placing the controls on to the container. JList Class provides component that displays list of objects & allows the user to select any one from the given list.
The program uses an object of JList Class which hold the list of stationery products, two arrays for holding product name and price & ListSelectionListener which is available in javax.swing.event package.
Classes and Methods Used in program
- JFrame Class: JFrame s is a window with borders and title. It places several components including container object
- ListSelectionListener: It is an interface that responds when a list selection value changes. Whenever the user selects or deselects the item in the list this interface is triggered.
- JList Class: A component that displays the list of objects (Stationery products). & allows the user to select one or more values.
- JLabel: This Class is used to display short text or images. An object of this class is used to display the price of the selected product in the program.
- void valueChanged (ListSelectionEvent e): This method is invoked when the value of the selection changes. It has to be implemented if we inherit the ListSelectionListener interface.
- getSelectedIndex (): This method of JList class is used to return the index of the selected item of the array. If the value of index is -1 it reaches to the end of array.
Here is the program
ListSelectionListener is used to react to the change in selection of the value in JList Component
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
class ListDemo extends JFrame implements ListSelectionListener
{
Container cp;
JList jlist;
JLabel lblPrice;
String[] prod={“Pen”,”Pencil”,”Ruler”,”Eraser”,”Shapner”};
int[] price={12,13,15,45,25};
ListDemo ()
{
cp=this.getContentPane();
cp.setLayout(new FlowLayout());
jlist =new JList(items);
lblPrice=new JLabel(“”);
jlist.addListSelectionListener(this);
cp.add(jlist);
cp.add(lblPrice);
}
public void valueChanged(ListSelectionEvent e)
{
if(jlist.getSelectedIndex()==-1)
{
lblPrice.setText(“no items selected”);
}
else
{
int index= jlist.getSelectedIndex();
lblPrice.setText(“Price: “+price[index]);
}
}
public static void main(String args[])
{
ListDemo lstObj= new ListDemo();
lstObj.setSize(400,400);
lstObj.setVisible(true);
lstObj.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}