<APPLET CODE=CounterApplet.class CODEBASE=./ WIDTH=500 HEIGHT=20> </APPLET>
import java.applet.*; import java.awt.*; import java.awt.event.*; public class CounterApplet extends Applet implements Runnable { int count = 0; Thread myThread; public void init() {...} public void start() {...} public void stop() {...} public void run() {...} public void paint(Graphics g) {...} private class ClickListener extends MouseAdapter {...} }
public void init() { addMouseListener(new ClickListener()); myThread = null; count = 0; } public void start() { myThread = new Thread(this,"CounterApplet"); myThread.start(); } public void stop() { myThread.stop(); myThread = null; }
public void run() { while (Thread.currentThread() == myThread) { count ++; repaint(); try { myThread.sleep(100); } catch (InterruptedException e) { System.err.println("Caught Interrupt."); System.exit(-1); } } }
public void paint(Graphics g) { g.setColor(new Color((count * 10) % 256, 128, 0)); // display counter. g.drawString(Integer.toString(count),5,15); }
// we will toggle start/stop. private class ClickListener extends MouseAdapter { public void mouseClicked(MouseEvent e) { if (myThread==null) start(); else stop(); } }
import java.awt.*; import java.awt.event.*; public class CounterFrame extends Frame implements Runnable { int count = 0; Thread myThread; public CounterFrame() {...} public void start() {...} public void stop() {...} public void run() {...} public void paint(Graphics g) {...} public static void main(String [] args) {...} private class ClickListener extends MouseAdapter {...} }
public CounterFrame() { addMouseListener(new ClickListener()); myThread = null; count = 0; } public static void main(String [] args) { CounterFrame cf = new CounterFrame(); cf.setSize(400,50); cf.show(); }
public void start() { myThread = new Thread(this,"CounterFrame"); myThread.start(); } public void stop() { myThread.stop(); myThread = null; }
public void run() { while (Thread.currentThread() == myThread) { count ++; repaint(); try { myThread.sleep(100); } catch (InterruptedException e) { System.err.println("Caught Interrupt."); System.exit(-1); } } }
public void paint(Graphics g) { g.setColor(new Color((count * 10) % 256, 128, 0)); // display counter. g.drawString(Integer.toString(count),10,40); }
private class ClickListener extends MouseAdapter { public void mouseClicked(MouseEvent e) { if (myThread==null) start(); else stop(); } }