import java.awt.*; import java.awt.event.*; public class NestedPanels4 extends NestedPanels { // notice we don't implement anything becuase we are going // to delagate even handling to other classes public NestedPanels4() { // set up the UI super(); // add the handlers // notice that we define the methods for // each interface right after we create one. // its not intuitive but can be very powerful. choice.addItemListener(new 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()); } }); // 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. setActionListeners(this); } // the function that assigns action listeners to the buttons // recursively. protected void setActionListeners(Component comp) { if (comp != null) { if (comp instanceof Button) { Button button = (Button) comp; button.addActionListener(new 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()); } }); } else if (comp instanceof Container) { Container container = (Container) comp; int n = container.getComponentCount(); for (int i = 0; i < n; i++) setActionListeners(container.getComponent(i)); } } } }