JList in Java Swing Example – Computer Notes

A list components allows user to select a single or multiple items from a given list of items by clicking on each. By default, a user can select multiple items, however it is also possible to create a list from which user can choose only a single item.

When the number of items in the list exceeds the available space then the list does not scroll automatically and only the top group of items will be available. In order to make a list scroll, you must insert it into a scrollpane.

The JList class provides the visual representation for selecting items in a set. An object of JList can be initiated with an array or a list of values. The JList object will create one item for each element in the array vector or list. The data in the JList object can be initiated by calling the constructor with the array vector as the parameter or by using the setListData() method. The JList class allows the user to create either a single-selection list (that is, a list in which only one item or element can be selected) or a multiple-selection list (which is a list in which more than one element can be selected.)

A list can be created by instantiating a JList class. Relevant methods:

 

Method

Description

publicJList()

Createsan emptyJList;

publicJList(Object [] listItems)

created withtheitemscontained in thearrayof objects;

publicJList(VectorlistItems)

created withtheVectorelements;

getSelectedIndexpublic int()

returns theindex of the firstselectItem(-1if none);

public int[] getSelectedIndices()

returns an array ofindicesthat are selected;

getSelectedValuepublic Object()

givesthereference to the object;

public Object[] getSelectedValues​​()

returns anarraywith the selectedObject.

 

Program explains the usage of the class Jlist. A scroll pane can also be attached to a Jlist item if the number of elements is more than the size of list.

import javax.swing.*;


import java .awt.*;


class ListBoxExample extends JFrame


{


    ListBoxExample()


    {


        setLayout(new FlowLayout());


String[] language = {"Cobol","Fortran","Pascal","C","C++"," Java ","C#"};


        JLabel lblLanguage = new JLabel("Choose the Language");


        JList LstMonth = new JList(language);


        add(lblLanguage);   add(LstMonth);


   


    }


}


  class ListBoxJavaExample


  {


       public static void main(String args[])


      {


            ListBoxExample frame = new ListBoxExample();


            frame.setTitle("ListBox Java Example");


            frame.setBounds(200,250,150,200);


            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


            frame.setVisible(true);


   }


 }


 

 

JList in Java Swing Example

 One of the another Example for JList is:

// <applet code=ListEx width=250 height=375> </applet>


import javax.swing.*;


import javax.swing.event.*;


import java.awt.*;


import java.awt.event.*;


import javax.swing.border.*;


public class ListEx extends JApplet


{


    String[] bikes = { "Honda Activa", "Honda Aviator", "Honda CB Shine", "Honda CB Trigger", "Honda CB Twister", "Honda CB Unicorn","Honda CB Unicorn Dazzler",


"Honda CBF Stunner","Honda CBR 1000RR","Honda CBR150R","Honda CB1000R","Honda CBR250R","Honda Dio" };


    DefaultListModel ListModel=new DefaultListModel();


    JList list = new JList(ListModel);


    JTextArea textarea = new JTextArea(bikes.length,20);


    JButton button = new JButton("Add More bikes");


    ActionListener Action = new ActionListener()


   {


       public void actionPerformed(ActionEvent e)


      {


                if(count < bikes.length)


                 {


                         ListModel.add(0, bikes[count++]);


                 } else


                     {


                            button.setEnabled(false);


                     }


       }


   };


        ListSelectionListener ListSelection = new ListSelectionListener()


        {


            public void valueChanged(ListSelectionEvent e)


           {


               textarea.setText("");


               Object[] items=list.getSelectedValues();


               for(int i = 0; i < items.length; i++)


                    textarea.append(items[i] + "\n");


            }


        };


            int count = 0;


            public void init()


           {


                   Container cont = getContentPane();


                   textarea.setEditable(false);


                   cont.setLayout(new FlowLayout());


                   Border brd = BorderFactory.createMatteBorder( 1, 1, 2, 2, Color.black);


                   list.setBorder(brd);


                   textarea.setBorder(brd);


                   for(int i = 0; i < 4; i++)


                         ListModel.addElement(bikes[count++]);


                         cont.add(textarea);


                         cont.add(list);


                         cont.add(button);


                         list.addListSelectionListener(ListSelection);


                         button.addActionListener(Action);


            }


           


}


list