Java Tutorial

AWT List

List is the GUI interactive component which allows to select either single or multiple items at Creating List component is nothing but creating an object of List class.

List API:


List ();
List (int size);
List (int size, boolean mode);

Instance methods:

public void setSize (int size); 
public int getSize ();
public void add (String); 
public void addItem (String); 
public void add (int, String);
public void addItem (int, String); 
public String getSelectedItem (); 
public String [] getSelectedItems ();
public int getSelectedIndex (); 
public int [] getSelectedIndexes (); 
public void remove (int index); 
public void remove (String item); 
public void removeAll ();
public void addItemListener (ItemListener); - single click of List item
public void removeItemListener (ItemListener); - single click of List item 
public void addActionListener (ActionListener); - double click of List item 
public void removeActionListener (ActionListener); - double click of List item


When we want to select the items of the list with single click then we must register with Item Listener to select items of the list with double click then we must register with ActionListener.

Write a java program which illustrates the concept of List?


import java.awt.*; 
import java.awt.event.*;
import java.applet.Applet;
/*<applet code="ListApp" height=200 width=200>
public class ListApp extends Applet
    Label l1, l2; List li; TextArea ta;
    public void init ()
        setBackground (Color.yellow); 
        l1=new Label ("Available fonts"); 
        l2=new Label ("Selected fonts"); 
        ta=new TextArea ();
        li=new List (); 
        li.setMultipleMode (true);
        GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment ();
        String s []=ge.getAvailableFontFamilyNames (); for (int i=0; i<s.length; i++)
            li.add (s [i]);
        add (l1);
        add (li);
        add (l2);
        add (ta);
    public void start ()
        li.addItemListener (new itl ()); 
        li.addActionListener (new atl ());
    class itl implements ItemListener
        public void itemStateChanged (ItemEvent ie)
            if (ie.getSource ()==li)
                String s1 []=li.getSelectedItems (); 
                for (int j=0; 
                j<s1.length; j++)
                    ta.append (s1 [j]+"\n");
        class atl implements ActionListener
            public void actionPerformed (ActionEvent ae)
                if (ae.getSource ()==li)
                    String s2 []=li.getSelectedItems (); 
                    for (int l=0; l<s2.length; l++)
                        ta.append (s2 [l]+"\n");