// JDK 1.1 import java.awt.*; import java.awt.event.*; public class BouncingBall3a extends java.applet.Applet implements Runnable { protected BouncingBallCanvas canvas; protected Panel controlPanel; protected static final int START = 1; protected static final int STOP = 2; Thread bouncingThread; int delay = 400; protected class StartStopButtonHandler implements ActionListener { private int cmd = 0; public StartStopButtonHandler(int cmd) { this.cmd = cmd; } public void actionPerformed(ActionEvent event) { switch (cmd) { case START: start(); break; case STOP: stop(); break; } } } protected class ColorChoiceHandler implements ItemListener { public void itemStateChanged(ItemEvent event) { Choice choice = (Choice) event.getSource(); if (choice != null) { if ("red".equals(event.getItem())) { canvas.setColor(Color.red); } else if ("green".equals(event.getItem())) { canvas.setColor(Color.green); } else if ("blue".equals(event.getItem())) { canvas.setColor(Color.blue); } } } } public BouncingBall3a() { setLayout(new BorderLayout()); canvas = new BouncingBallCanvas(); add("Center", canvas); controlPanel = new Panel(); controlPanel.setLayout(new GridLayout(1,0)); Button startButton = new Button("start"); controlPanel.add(startButton); Button stopButton = new Button("stop"); controlPanel.add(stopButton); Choice choice = new Choice(); choice.addItem("red"); choice.addItem("green"); choice.addItem("blue"); controlPanel.add(choice); add("South", controlPanel); startButton.addActionListener(new StartStopButtonHandler(START)); stopButton.addActionListener(new StartStopButtonHandler(STOP)); choice.addItemListener(new ColorChoiceHandler()); } public void init() { String att = getParameter("delay"); if (att != null) delay = Integer.parseInt(att); doLayout(); canvas.init(); } public void start() { if (bouncingThread == null) { bouncingThread = new Thread(this); bouncingThread.start(); } } public void stop() { if (bouncingThread != null) { bouncingThread = null; } } public void run() { while (Thread.currentThread() == bouncingThread) { try { Thread.currentThread().sleep(delay); } catch (InterruptedException e){} canvas.repaint(); } } }