import java.awt.*; import java.awt.event.*; public class NestedPanels3 extends NestedPanels { // notice we don't implement anything becuase we are going // to delagate event handling to other classes public NestedPanels3() { // set up the UI super(); // add the handlers ChoiceEventHandler chandler = new ChoiceEventHandler(); choice.addItemListener(chandler); ButtonEventHandler bhandler = new ButtonEventHandler(); // this function will call the "addActionListener()" // for each button in the UI. // we use the this reference to tell the function to // start at the top of the containment hierarchy. bhandler.beActionListener(this); } // the class responsible for handing item events class ChoiceEventHandler implements ItemListener { public void itemStateChanged(ItemEvent event) { if (event!=null) System.out.println("ItemStateChanged: " + event); Choice choice = (Choice) event.getSource(); if (choice != null) messageBar.setText("Choice selected: " + event.getItem()); } } // the class responsible for handling action events class ButtonEventHandler implements ActionListener { public void actionPerformed(ActionEvent event) { if (event!=null) System.out.println("ActionPerformed: " + event); Button source = (Button) event.getSource(); if (source != null) messageBar.setText("Button pushed: " + source.getLabel()); } // the function that assigns actiona listeners to the buttons // recursively. protected void beActionListener(Component comp) { if (comp != null) { if (comp instanceof Button) { Button button = (Button) comp; button.addActionListener(this); } else if (comp instanceof Container) { Container container = (Container) comp; int n = container.getComponentCount(); for (int i = 0; i < n; i++) beActionListener(container.getComponent(i)); } } } } }