Way2Java

Java AWT List Multiple Single Selection

List permits the selection of multiple items (Choice allows single selection). Programmer prefers List when checkboxes are many to display (in case of Choice, when radio buttons are many to display). List adds a scrollbar with which items can be scrolled and seen. List can be designed for single selection or multiple selection (Java AWT List Multiple Single Selection).

In general, all GUI components generate only one event. But in contrary, List can generate two events. For single clicks, it generates ItemEvent handled by ItemListener and for double clicks, ActionEvent handled by ActionListener. These two types of clicks can be used as in Window Explorer; single click selects the file and double click opens the file.

Choice Vs. List

Following table gives clear cut differences with Choice.

Choice List
Used for single selection only Used for single and multiple selections
Generally gives dropdown list Gives scrollable list of items
Generally, scrollbar is not required Generally scrollbar is seen
Generates only one event – ItemEvent Generates two events – ItemEvent and ActionEvent
Replacement to radio buttons Replacement to radio buttons or checkboxes

Following is the class signature

public class List extends Component implements ItemSelectable, Accessible

Example on Java AWT List – Preparing Super Bazar Bill

We have seen earlier in Choice component, the creation of applets with GUI. This program is also meant to practice GUI with applets. As a practice, you can change this program into an application. In the following applet, the items, selected by the user, in a super bazar are tabulated and made in a bill format.

import java.awt.*;
import java.awt.event.*;
public class SuperBazarBilling extends Frame implements ActionListener
{
  List bazar;
  double rates[] = { 80.50, 75.60, 150.25, 39.99, 120.25, 90.80, 50.00 };
  public SuperBazarBilling()
  {                          // create List object
    bazar = new List(5, true);
                              // populate list
    bazar.add("Gloves");            
    bazar.add("Socks");
    bazar.add("Waist Belt");
    bazar.add("Cap");
    bazar.add("Wallet");
    bazar.add("Pen Set");
    bazar.add("Napkins");
                               // register with listener
    bazar.addActionListener(this);
                            // window closing using adapter
    PleaseClose pc = new PleaseClose();
    addWindowListener(pc);
                             // add to frame
    add(bazar, "North");
                            // frame creation trio
    setTitle("Scrollable List");
    setSize(300, 350);
    setVisible(true);
  }                // override the abstract method of AL
  public void actionPerformed(ActionEvent e)
  {
    repaint();
  }
  public void paint(Graphics g)
  {
    String itemNames[] = bazar.getSelectedItems();
    int itemIndexes[] = bazar.getSelectedIndexes();
      
    int y = 170;
    double totalAmount = 0.0;	
    g.drawString("Sl.No.            Item Name    Item code        Rate", 50, 150);
    for(int i = 0; i < itemNames.length; i++,  y  +=  25)   
    {
      g.drawString((i + 1) + "  " + itemNames[i] + "  " + itemIndexes[i] + "  "  + rates[itemIndexes[i]], 50, y);
      totalAmount  +=  rates[ itemIndexes[i]];
    }  
    g.setColor(Color.blue);
    g.drawString("Total Bill Rs." + totalAmount, 50, y  +=  25);
    g.setColor(Color.magenta);
    g.drawString("Thnaks Visit Again.", 50,  y +=  25);
    g.setColor(Color.red);
    g.drawString("Comments Book Available", 50,  y +=  25);
  }
  public static void main(String args[])
  {
    new SuperBazarBilling();
  }
}

class PleaseClose extends WindowAdapter
{
  public void windowClosing(WindowEvent e)
  {
    System.exit(0);
  }
}

The class implements ActionListener and thereby double clicks on the items only work.

Java AWT List Multiple Single Selection

bazar = new List(5, true);

The list bazar is set to multiple mode with the second parameter true. True indicates multiple selection and false indicates single selection. 5 indicates the visible items in the list at a time; to see the other than 5, scrollbar may be used.

bazar.add("Gloves");
bazar.add("Socks");

The List object bazar is populated with items using add() method.

String itemNames[] = bazar.getSelectedItems();
int itemIndexes[] = bazar.getSelectedIndexes();

getSelectedItems() method returns all the items selected by the user as a string array and getSelectedIndexes() returns the index numbers of items selected by the user as an integer array. An array, rates[], is used to prepare a bill of the items selected.

repaint() Method

The paint() method is called implicitly in two circumstances – first time when the frame is created or when the frame is resized by dragging the sides. If the programmer would like to call the paint() method, he should call repaint() method but not paint() method directly (if called, it is a compilation error).

repaint() --> update() --> paint()

As illustrated in the above figure, the repaint() method calls implicitly update() method and again update() method calls implicitly the paint() method. The update() method clears the earlier drawings existing on the frame and on the cleared surface, the paint() method draws afresh the latest drawings.

Note: WindowAdapter usage, to close the window, is given in "Java Frame Closing - WindowAdapter"

Some more frequently used methods with List not used in the above program.

  1. int getItemCount() : Returns the number of items present in the list.,
  2. String getItem(int index) : Returns the item at the specified index.
  3. void add(String item, int index) : Inserts the item at the specified index. The original item is pushed to the next. By default, the items added in the list are given index numbers – the first one being zero, the second as one and so on.
  4. void replaceItem(String newItem, int index) : Replaces the item at the specified index with the specified one, newItem. The original one is lost.
  5. void remove(String item) : Removes the specified item. Item is specified as a string.
  6. void remove(int index) : Removes the specified item. Item is specified with index number.
  7. int getSelectedIndex() : Returns the index number of the item selected by the user. Used when ItemListener is implemented.
  8. String getSelectedItem() : Returns the item name as string selected by the user. Used when ItemListener is implemented.
  9. void select(int index) : By default the item at the specified index is selected.
  10. int getRows() : Returns the number of visible items in the list.
  11. void addItemListener(ItemListener il) : Registers the list with the item listener. Now the single clicks of the list are handled by item listener.

Methods like select(), addItemListener(), getSelectedItem() and getSelectedIndex() etc. are used in "Java AWT Choice – Replacement to Radio Button".

The internal process of what happens at a button click is discussed in Event Handling.