//: c14:Counter2i.java // From Thinking in Java, 2nd Edition // Available at http://www.BruceEckel.com // (c) Bruce Eckel 1999 // Copyright notice in Copyright.txt // Counter2 using an inner class for the thread // // import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Counter2i extends JApplet { private class SeparateSubTask extends Thread { int count = 0; boolean runFlag = true; SeparateSubTask() { start(); } public void run() { while (true) { try { sleep(100); } catch (InterruptedException e){} if(runFlag) t.setText(Integer.toString(count++)); } } } private SeparateSubTask sp = null; private JTextField t = new JTextField(10); private JButton onOff = new JButton("Toggle"), start = new JButton("Start"); public void init() { Container cp = getContentPane(); cp.setLayout(new FlowLayout()); cp.add(t); start.addActionListener(new StartL()); cp.add(start); onOff.addActionListener(new OnOffL()); cp.add(onOff); } class StartL implements ActionListener { public void actionPerformed(ActionEvent e) { if(sp == null) sp = new SeparateSubTask(); } } class OnOffL implements ActionListener { public void actionPerformed(ActionEvent e) { if(sp != null) sp.runFlag = !sp.runFlag; // invertFlag(); } } public static void main(String[] args) { JApplet applet = new Counter2i(); JFrame frame = new JFrame("Counter2i"); frame.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e){ System.exit(0); } }); frame.getContentPane().add(applet); frame.setSize(300, 100); applet.init(); applet.start(); frame.setVisible(true); } } ///:~