//: c14:Counter2.java // From Thinking in Java, 2nd Edition // Available at http://www.BruceEckel.com // (c) Bruce Eckel 1999 // Copyright notice in Copyright.txt // A responsive user interface with threads // // import javax.swing.*; import java.awt.*; import java.awt.event.*; class SeparateSubTask extends Thread { private int count = 0; private Counter2 c2; private boolean runFlag = true; public SeparateSubTask(Counter2 c2) { this.c2 = c2; start(); } public void invertFlag() { runFlag = !runFlag;} public void run() { while (true) { try { sleep(100); } catch (InterruptedException e){} if(runFlag) c2.t.setText(Integer.toString(count++)); } } } public class Counter2 extends JApplet { JTextField t = new JTextField(10); private SeparateSubTask sp = null; 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(Counter2.this); } } class OnOffL implements ActionListener { public void actionPerformed(ActionEvent e) { if(sp != null) sp.invertFlag(); } } public static void main(String[] args) { JApplet applet = new Counter2(); JFrame frame = new JFrame("Counter2"); 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); } } ///:~