by Dinesh Thakur Category: Swing

Lists are supported in Swings by the JList class. It is a very popular control as it allows the user to present a list of items in an easier and efficient manner. It also allows hiding the long list of items by making the lists scrollable. JList has been inherited from a long list of classes.

Table below shows the constructors of the JList class:

                     constructors of the JList

The simple example for creating a list using Swings that displays 15 items and reports which ones the user clicks is illustrated below.

import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
/*<APPLET code=list1.class WIDTH=300 HEIGHT=200> </APPLET>*/
public class list1 extends JApplet implements ListSelectionListener
{
    JList jlist;
    public void init()
      {
          Container c= getContentPane();
          String[] str=new String[15];
          for(int i=0;i<15;i++)
               {
                   str[i]="Item_Selection" +(i+1);
               }
                   jlist = new JList(str);
                   JScrollPane scp= new JScrollPane(jlist);
                   jlist.setVisibleRowCount(5);
                   jlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                   jlist.addListSelectionListener(this);
                   c.setLayout(new FlowLayout());
                   c.add(scp);
       }
             public void valueChanged(ListSelectionEvent lse)
             {
                 String st="Choose Item";
                 st+=jlist.getSelectedIndex();
                 showStatus(st);
             }
}
 
The output for the same would look like:
                  List using Swing


Popular Article