3 Ways to Create an AWT List in Java

The following illustrates creating an AWT List in Java. This tutorial also covers all core methods of the java.awt.List class.

import java.awt.*;
import java.awt.event.*;
class AWTList extends Frame
List l1,l2,l3,l4;

    public AWTList()
    private void createAndShowGUI()
        setTitle("List in AWT Example");
        setLayout(new FlowLayout());
        // An empty list
        l1=new List();
        // List with given no.of rows
        l2=new List(5);
        // List with given no.of rows,multi-select enabled
        l3=new List(5,true);
        // One more empty list!
        l4=new List();
        // Add items
        l1.add("Item 1");
        l1.add("Item 2");
        l1.add("Item 3");
        l1.add("Item 4");
        l1.add("Item 5");
        l2.add("Item 1");
        l2.add("Item 2");
        l2.add("Item 3");
        l2.add("Item 4");
        l2.add("Item 5");
        l3.add("Item 1");
        l3.add("Item 2");
        l3.add("Item 3");
        l3.add("Item 4");
        l3.add("Item 5");
        l4.add("Item 1");
        l4.add("Item 2");
        l4.add("Item 3");
        l4.add("Item 4");
        l4.add("Item 5");
        // Enable multi select for l1
        // Add item at index 2
        // Item 3 goes to 4th 'position'
        l1.add("Item 2-A",2);
        // Make Item 1 visible no matter what
        // which item is selected
        // Replace an item
        // Item 2 becomes 2nd Item
        l3.replaceItem("2nd Item",1);
        // Select item at 2nd index
        /* -- Select and de-select -- */
        // Select item at 0 index
        // De-Select an item by index
        // Remove item at 2nd index
        // Remove Item 1
        // Item 2 now comes at 0th index
        l3.remove("Item 1");
        // Remove all items in l4
        // Print get methods
        System.out.println("Item at index 0 in l1 is "+l1.getItem(0));
        System.out.println("Visible index for l1 is "+l1.getVisibleIndex());
        System.out.println("No.of rows of l2 is "+l2.getRows());
        System.out.println("No.of items in l3 is "+l3.getItemCount());
        System.out.println("Is 0 index selected in l3? "+l1.isIndexSelected(0));
        System.out.println("Is multi select enabled in l2? "+l1.isMultipleMode());

        // Add all lists
    public static void main(String args[])
        new AWTList();

AWTList(): Code illustrating creating an AWT List in Java is invoked here.
new AWTList(): Create an object for the AWTList class.

You might also want to see using ItemListener for AWT List

Creating AWT List in Java

Next: Create Menus and MenuItems in AWT
Previous: Creating an AWT Choice in Java

Posted by at on

Tags: Abstract Window Toolkit,