// // another example of the Java AWT, showing use of List class. // see class definition and main method for details. // import java.awt.* ; import java.awt.event.* ; // // a ListExample object is a CloseableFrame containing a List and a // Label. depending on the arguments to the constructor, // multiple selections may or may not be allowed. when the // user makes a selections, the current selections are displayed // in the Label. // here, *Listeners are implemented using anonymous classes. compare // with ListExample. // class ListExampleAlt extends CloseableFrame { List l ; Label display ; ListExampleAlt(boolean multi, String[] items) { super("ListExampleAlt") ; setLayout(new BorderLayout()) ; // make list with input items. second argument // specifies how many items to display -- // set to items.length/2 initially to show // automatic scrollbar. l = new List(items.length / 2, multi) ; for (int i = 0 ; i < items.length ; i++) l.add(items[i]) ; display = new Label("nothing selected") ; // action to be performed when user clicks on an item // (select/deselect). l.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { setDisplay("ItemEvent") ; } } ) ; // action to be performed when user double-clicks on // an item. l.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setDisplay("ActionEvent") ; } } ) ; add(l, "Center") ; add(display, "South") ; pack() ; show() ; } // displays current selection(s) in Label. // should probably be declared private, but calling a // private method from an anonymous inner class (as above) // apparently triggers a compiler bug, causing the // compiler to hang!). void setDisplay(String event) { String itemsSel[] = l.getSelectedItems() ; String s ; if (itemsSel.length == 0) { s = "nothing selected" ; } else { StringBuffer sb = new StringBuffer("selected") ; for (int i = 0 ; i < itemsSel.length ; i++) sb.append(" " + itemsSel[i]) ; s = sb.toString() ; } display.setText(event + ": " + s) ; } // // ---- main --------------------------------------------------- // // command-line arguments are y/n (multiple selections allowed), // elements of List. // public static void main(String[] args) { if (args.length < 2) { System.out.println("Arguments are y/n, " + "list items") ; System.exit(-1) ; } boolean multi = args[0].equals("y") ; String[] s = new String[args.length-1] ; for (int i = 0 ; i < s.length ; i++) s[i] = args[i+1] ; ListExampleAlt l = new ListExampleAlt(multi, s) ; } }