//: c14:Counter4.java // From 'Thinking in Java, 2nd ed.' by Bruce Eckel // www.BruceEckel.com. See copyright notice in CopyRight.txt. // By keeping your thread as a distinct class, // you can have as many threads as you want. // import javax.swing.*; import java.awt.*; import java.awt.event.*; import com.bruceeckel.swing.*; public class Counter4 extends JApplet { private JButton startB = new JButton("Start"); private Ticker[] s; class Ticker extends Thread { private JToggleButton b = new JToggleButton("Toggle"); private JTextField t = new JTextField(10); private int count = 0; private boolean runFlag = true; public Ticker() { b.addActionListener(new ToggleL()); JPanel p = new JPanel(); p.add(t); p.add(b); getContentPane().add(p); } class ToggleL implements ActionListener { public void actionPerformed(ActionEvent e) { runFlag = !runFlag; } } public void run() { while (true) { if (runFlag) t.setText(Integer.toString(count++)); try { sleep(500); } catch(InterruptedException e) { System.err.println("Interrupted"); } } } } class StartL implements ActionListener { public void actionPerformed(ActionEvent e) { startB.setBackground(Color.red); startB.setEnabled(false); for (int i = 0; i < s.length; i++) s[i].start(); } } public void init() { Container cp = getContentPane(); cp.setLayout(new FlowLayout()); s = new Ticker[4]; for (int i = 0; i < s.length; i++) s[i] = new Ticker(); startB.addActionListener(new StartL()); cp.add(startB); } public static void main(String[] args) { Counter4 applet = new Counter4(); Console.run(applet, 200, 160); } } ///: