|
The "List" component displays all of its choices on the display window at all times. Experiment with the applet below to see what it does. Then proceed to understand the code that generates the applet.
The applet below implements the "ItemListener", requiring the "itemStateChanged" method to be implemented (see the event handling reference). The "init" method sets the layout manager to be the null layout manager. It then creates a "List" with two items. The "true" indicates that multiple items from the list can be simultaneously selected. The "colorList" is given two choices: "red" and "blue". Since the null layout manager is being used, "colorList" must be located and sized with the "setBounds" method. An item listener is added so that events involving "colorList" can be detected. Finally, the "colorList" "List" is added to the display window. The "itemStateChanged" method works by calling the "getSelectedItems" method. This method returns an array of strings. Each string is the label of an item in the "List" that is currently selected. If both "red" and "blue" are selected, the background is set to a purplish color (recall that purple is produced by combining red and blue). If neither color is selected, the background is set to gray. Otherwise, the background is set to either "red" or "blue" depending upon which one has been selected. import java.awt.*; import java.awt.event.*; import java.applet.*; public class Example extends Applet implements ItemListener { public void init () { setLayout(null); colorList = new List(2, true); colorList.add("red"); colorList.add("blue"); colorList.setBounds(100, 100, 100, 50); colorList.addItemListener(this); add(colorList); } public void itemStateChanged (ItemEvent evt) { String [] colors = colorList.getSelectedItems(); if (colors.length == 2) setBackground (new Color(255,0,255)); else if (colors.length == 0) setBackground (Color.gray); else if (colors[0].equals("red")) setBackground (Color.red); else if (colors[0].equals("blue")) setBackground (Color.blue); repaint(); } private List colorList; } |