Contents | Prev | Next Inner Classes Specification


Further Example: Sample AWT code

The 1.1 version of the Java Abstract Window Toolkit provides a new event handling framework, based on "event listener" interfaces, to which the programmer must write callback objects. The callbacks amount to a flexible new layer between the GUI and the application's data structures. These adapters must be subclassed to hook them up to the application. The point of this is to avoid the need to subclass the GUI components themselves, or to write complicated if/else and switch statements to interpret event codes.

This design requires that the adapter classes be simpler to write and maintain than the corresponding if/else and switch code! This is where inner classes become important.

Here is an typical example of AWT event handling code. It uses a named inner class App.GUI to organize the GUI code, and anonymous adapters to tie individual GUI components to the application's methods:

    public class App {
        void search() { ...do search operation...}
        void sort() { ...do sort operation ... }
        static public void main(String args[]) {
            App app = new App(args);
            GUI gui = app.new GUI();   // make a new GUI enclosed by app
        }
        class GUI extends Frame {   // App.GUI is enclosed in an App.
            public GUI() {
                setLayout(new FlowLayout());
                Button b;
                add(b = new Button("Search"));
                b.addActionListener(
                    new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                            search();     // App.this.search()
                        }
                    }
                );
                ... build a Sort button the same way ...
               pack(); setVisible(true);
            }
        }
        ...
    }


Contents | Prev | Next

Inner Classes Specification (HTML generated by dkramer on March 15, 1997)
Copyright © 1996, 1997 Sun Microsystems, Inc. All rights reserved
Please send any comments or corrections to john.rose@eng.sun.com