// // another example of the Java AWT. see class definition and main // method for details. // compare to SwitchedButtonAlt.java, which implements much the same // behavior with different techniques. // import java.awt.* ; import java.awt.event.* ; // // a SwitchedButton object represents a main button plus a "switch" // button that toggles the main button's behavior between // "not listening" and "listening", using addActionListener() and // removeActionListener(). // // this class extends Container because that's an easy way to group // the two buttons and specify a layout for them. // class SwitchedButton extends Container implements ActionListener { Button mainButton ; String mainLabel ; Button switchButton ; boolean buttonOn = false ; // constructor: // s is the label for the main button. SwitchedButton(String s) { super() ; mainLabel = s ; // specify desired layout (buttons side by side). setLayout(new GridLayout(1, 2)) ; // make main button and add to container. mainButton = new Button(s + " (off)") ; add(mainButton) ; // make "switch" button and add to container. switchButton = new Button("Switch for " + s) ; add(switchButton) ; // set up to process button-press events for switch. switchButton.addActionListener(this) ; } // process button-press events: // for "switch" button, toggle main button off and on. // for main button, write message to standard output. public void actionPerformed(ActionEvent e) { Object src = e.getSource() ; if (src == mainButton) { System.out.println(mainLabel + " pressed") ; } else if (src == switchButton) { String newlbl ; buttonOn = !buttonOn ; // if switch is off now, stop listening for // events from main button. if (!buttonOn) { mainButton.removeActionListener(this) ; newlbl = mainLabel + " (off)" ; } // if switch is on now, start listening. else { mainButton.addActionListener(this) ; newlbl = mainLabel + " (on)" ; } // relabel button mainButton.setLabel(newlbl) ; } } // // ---- main method -------------------------------------------- // // command-line argument is N, number of button/switch pairs // to create (default 4). // public static void main(String[] args) { int num = 4 ; if (args.length > 0) num = Integer.parseInt(args[0]) ; // frame with title CloseableFrame f = new CloseableFrame("SwitchedButtonAlt") ; // set up to display pairs of buttons in a (vertical) // column. f.setLayout(new GridLayout(num, 1)) ; // create and add buttons b1 .. bN. for (int i = 0 ; i < num ; i++) f.add(new SwitchedButton("b" + (i+1) )) ; // set minimum size needed to hold everything, and // display. f.pack() ; f.show() ; } }