Wednesday, April 27, 2011

An example without using inner classes


import java.awt.*;
   import java.awt.event.*;
   //Top-most class
   class ImageViewer {
      public static final void main(String[] args){
         ImageViewer im = new ImageViewer();
      }
      public ImageViewer(){
         CommandPanel cp = new CommandPanel(this);
      }
      public void displayImage(){
         // Code to display an image
      }
   }
   // Creates GUI
   class CommandPanel extends Frame{
      ImageViewer viewer;
      CommandPanel(ImageViewer vw){
         viewer = vw;
         createGUI();
      }
      private void createGUI(){
         setLayout(new FlowLayout());
         Button dispBtn = new Button("Display");
         DisplayCommand dispC = new DisplayCommand(viewer);
         dispBtn.addActionListener(dispC);
         // Other components
         add(dispBtn);
         pack();
         setSize(100,100);
         setVisible(true);
      }
   }
   //Adapter class to handle events
   class DisplayCommand implements ActionListener {
      ImageViewer viewer;
      public DisplayCommand(ImageViewer vw){
         viewer = vw;
      }
      public void actionPerformed(ActionEvent e){
         viewer.displayImage();
      }
   }

No comments:

Post a Comment