// // another example of the Java AWT, showing use of adapter classes. // (here, they're implemented as named 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 PowerOf2GUI 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 PowerOf2GUI extends CloseableFrame { PowerOf2GUI() { super("Powerof2GUI") ; int num = 2 ; // number of PowerOf2 objects setLayout(new GridLayout(num, 3, 20, 20) ) ; for (int i = 0 ; i < num ; i++) { PowerOf2 obj = new PowerOf2() ; // create buttons and add to frame. Button h = new Button("halve it") ; h.setActionCommand("halveIt") ; add(h) ; Button d = new Button("double it") ; d.setActionCommand("doubleIt") ; add(d) ; // create label (to display obj's value) and // add to frame. Label lbl = new Label( Double.toString(obj.val()), Label.RIGHT) ; add(lbl) ; // create adapter objects and register as // listeners. h.addActionListener(new Adapter(obj, lbl) ) ; d.addActionListener(new Adapter(obj, lbl) ) ; } // set minimum size needed to hold everything, and // display. pack() ; show() ; } // // ---- main --------------------------------------------------- // // no command-line arguments. // public static void main(String[] args) { PowerOf2GUI f = new PowerOf2GUI() ; } // // ---- inner class -------------------------------------------- // // a Adapter object is an ActionListener that will be // associated with a Button, a Label, and a PowerOf2 // object. it processes button-press events from the // Button by invoking doubleIt() or halveIt() (depending // on the Button's ActionCommand) on the PowerOf2 object // and displaying the resulting value in the Label. // class Adapter implements ActionListener { PowerOf2 obj ; Label l ; Adapter(PowerOf2 obj, Label l) { this.obj = obj ; this.l = l ; } public void actionPerformed(ActionEvent e) { String s = e.getActionCommand() ; if (s.equals("doubleIt")) { obj.doubleIt() ; } else if (s.equals("halveIt")) { obj.halveIt() ; } l.setText(Double.toString(obj.val())) ; } } }