/* Name: Chris Johnson johnson@dcs.gla.ac.uk Last modified: 21/1/2000 Description: Creates some lights that are controlled by three buttons. From an idea originally suggested by: Quintin Blane qablane@surfaid.org Updated to AWT 1.1 21/1/2000 */ import java.awt.*; import java.awt.event.*; import java.applet.Applet; public class Lights extends Applet { Panel controls = new Panel(); // for the red, green and ambre buttons static final String Red_Command = "red"; static final String Amber_Command = "amber"; static final String Green_Command = "green"; Button Red_Button = new Button("Red"); // create new buttons Button Amber_Button = new Button("Amber"); Button Green_Button = new Button("Green"); Traffic_Lights lights = new Traffic_Lights(this); // create some lights that will appear on this applet public void init(){ setLayout(new BorderLayout()); Red_Button.setActionCommand(Red_Command); Amber_Button.setActionCommand(Amber_Command); Green_Button.setActionCommand(Green_Command); controls.setLayout(new FlowLayout(FlowLayout.LEFT)); controls.add(Red_Button); controls.add(Amber_Button); controls.add(Green_Button); add("North", controls); add("Center", lights); //initialise the listener Traffic_Light_Event Tle = new Traffic_Light_Event(); //add the listener to each object Red_Button.addActionListener(Tle); Green_Button.addActionListener(Tle); Amber_Button.addActionListener(Tle); validate(); } //inner class actionlistener class Traffic_Light_Event implements ActionListener { public void actionPerformed(ActionEvent event) { if(event.getActionCommand() == Red_Command) //uses the action command text lights.set_lights("Red"); else if (event.getActionCommand() == Green_Command) //if not set then it uses button text lights.set_lights("Green"); else if (event.getActionCommand() == Amber_Command) lights.set_lights("Amber"); } } }