// This example is from the book Developing Java Beans by Robert Englander. 
// Copyright (c) 1997 O'Reilly & Associates.
// You may study, use, modify, and distribute this example for any purpose.
// This example is provided WITHOUT WARRANTY either expressed or implied.

// Chapter 5 -- The first version of the ListeningPanel class

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import BeansBook.util.*;
public class ListeningPanel extends Panel
{
   // the buttons - I would think should be transient
   protected Button b1;
   protected Button b2;
   protected Button b3;

   // the button adapter
   protected GenericButtonAdapter adapter;

   // the constructor
   public ListeningPanel()
   {
   }

   // initialize the panel
 
  public void initialize()
   {
      // construct the buttons
      b1 = new Button("Button 1");
      b2 = new Button("Button 2");
      b3 = new Button("Button 3");

      // add the buttons to the panel
      add(b1);
      add(b2);
      add(b3);

      // setup the adapter
      try
      {
         adapter = new GenericButtonAdapter(this);
         adapter.registerActionEventHandler(b1, "handleB1");
         adapter.registerActionEventHandler(b2, "handleB2");
         adapter.registerActionEventHandler(b3, "handleB3");
      }
      catch (Exception e)
      {
      }
   }

   // handle click for b1
   public void handleB1(ActionEvent evt)
   {
      System.out.println(b1.getLabel() + " Clicked");
   }
   
   // handle click for b2
   public void handleB2(ActionEvent evt)
   {
      System.out.println(b2.getLabel() + " Clicked");
   }
   
   // handle click for b3
   public void handleB3(ActionEvent evt)
   {
      System.out.println(b3.getLabel() + " Clicked");
   }

   // handle the writing of the object state
     private void writeObject(ObjectOutputStream stream)
               throws java.io.IOException
   {
      // store the state of the buttons.
      stream.defaultWriteObject();

      // retrieve the labels of the buttons and store it
      // to use as a sanity check during readObject
      String sanity = b1.getLabel() + b2.getLabel() + b3.getLabel();
      stream.writeObject(sanity);
   }

   // handle the reading of the object state
     private void readObject(ObjectInputStream stream)
      throws java.io.IOException
   {
      try
      {
         // restore the buttons
         stream.defaultReadObject();
         
         // read back the sanity check string
         String sanity = (String)stream.readObject();
      
         // if the sanity check fails, throw an exception
         String check = b1.getLabel() + b2.getLabel() + b3.getLabel();
         if (!sanity.equals(check))
         {
            throw new IOException();
         }
      }
      catch (ClassNotFoundException e)
      {
         System.out.println(e);
      }
   }
}