/* */ import java.awt.*; import java.applet.Applet; import java.awt.event.*; public class TrafficLights extends Applet { int light = (-1); // Current light: 0 red, 1 yellow, 2 green, // 3 blinking, (-1) all lights are off Button redButton; Button yellowButton; Button greenButton; Button blinkingButton; boolean blinkingOn = false; // Yellow light is On in blinking mode Thread blinkingThread = null; public void init() { setLayout(null); int x = 10; int y = 10; redButton = new Button("Red"); redButton.setBounds(x, y, 60, 20); y += 30; add(redButton); yellowButton = new Button("Yellow"); yellowButton.setBounds(x, y, 60, 20); y += 30; add(yellowButton); greenButton = new Button("Green"); greenButton.setBounds(x, y, 60, 20); y += 30; add(greenButton); blinkingButton = new Button("Blinking"); blinkingButton.setBounds(x, y, 60, 20); add(blinkingButton); ActionListener al = new ActionListener() { public void actionPerformed(ActionEvent e) { Object s = e.getSource(); if (s == redButton) onRed(); else if (s == yellowButton) onYellow(); else if (s == greenButton) onGreen(); else if (s == blinkingButton) onBlinking(); } }; redButton.addActionListener(al); yellowButton.addActionListener(al); greenButton.addActionListener(al); blinkingButton.addActionListener(al); setBackground(Color.gray); } void onRed() { light = 0; repaint(); } void onYellow() { light = 1; repaint(); } void onGreen() { light = 2; repaint(); } void onBlinking() { if (light == 3) return; light = 3; Runnable b = new Runnable() { public void run() { blinkingOn = true; repaint(); while (light == 3) { // Loop until blinking is on try { Thread.sleep(1000); // Wait 1 sec } catch (InterruptedException e) { } blinkingOn = (!blinkingOn); repaint(80, 40, 20, 20); // Repaint the yellow lamp only } } }; blinkingThread = new Thread(b); blinkingThread.start(); } public void paint(Graphics g) { int x = 80; int y = 10; if (light == 0) g.setColor(Color.red); else g.setColor(Color.black); g.fillOval(x, y, 20, 20); y += 30; if (light == 1 || (light == 3 && blinkingOn)) g.setColor(Color.yellow); else g.setColor(Color.black); g.fillOval(x, y, 20, 20); y += 30; if (light == 2) g.setColor(Color.green); else g.setColor(Color.black); g.fillOval(x, y, 20, 20); } }