// // another example of the Java AWT, showing use of adapter classes. // (here, they're implemented as anonymous inner classes.) // see class definition for details. // import java.awt.* ; import java.awt.event.* ; // // a PowerOf2 object represents an integer power of 2. // class PowerOf2 { int p = 0 ; void doubleIt() { p++ ; } void halveIt() { p-- ; } double val() { return Math.pow(2.0, (double) p) ; } } // // a PowerOf2GUIAlt object is a CloseableFrame with GUIs for two // PowerOf2 objects, each GUI consisting of two buttons to // invoke the doubleIt() and halveIt() methods and a display // area. // class PowerOf2GUIAlt extends CloseableFrame { PowerOf2GUIAlt() { super("PowerOf2GUIAlt") ; int num = 2 ; // number of PowerOf2 objects setLayout(new GridLayout(num, 3, 20, 20) ) ; for (int i = 0 ; i < num ; i++) { // create a PowerOf2 object together with // associated buttons and label, and // add to frame. p2PlusGUI() ; } // set minimum size needed to hold everything, and // display. pack() ; show() ; } // create a PowerOf2 object together with associated buttons // and label, and add to container. // this code is a separate method rather than being included // in main() because anonymous inner classes can access // only final variables. void p2PlusGUI() { final PowerOf2 o = new PowerOf2() ; Button h = new Button("halve it") ; add(h) ; Button d = new Button("double it") ; add(d) ; final Label l = new Label( Double.toString(o.val()), Label.RIGHT) ; add(l) ; h.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { o.halveIt() ; l.setText(Double.toString(o.val())) ; } } ) ; d.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { o.doubleIt() ; l.setText(Double.toString(o.val())) ; } } ) ; } // // ---- main --------------------------------------------------- // // no command-line arguments. // public static void main(String[] args) { PowerOf2GUIAlt f = new PowerOf2GUIAlt() ; } }