The following illustrates creating an AWT List in Java. This tutorial also covers all core methods of the java.awt.List class.
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
Next: Create Menus and MenuItems in AWT
Previous: Creating an AWT Choice in Java
import java.awt.*;
import java.awt.event.*;
class AWTList extends Frame
{
List l1,l2,l3,l4;
public AWTList()
{
createAndShowGUI();
}
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
l1.setMultipleMode(true);
// 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
l1.makeVisible(0);
// Replace an item
// Item 2 becomes 2nd Item
l3.replaceItem("2nd Item",1);
// Select item at 2nd index
l1.select(2);
/* -- Select and de-select -- */
// Select item at 0 index
l2.select(0);
// De-Select an item by index
l2.deselect(0);
// Remove item at 2nd index
l2.remove(2);
// Remove Item 1
// Item 2 now comes at 0th index
l3.remove("Item 1");
// Remove all items in l4
l4.removeAll();
// 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
add(l1);
add(l2);
add(l3);
add(l4);
setSize(400,400);
setVisible(true);
}
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
Next: Create Menus and MenuItems in AWT
Previous: Creating an AWT Choice in Java