/Users/lyon/j4p/src/gui/run/ThreadedRunButton.java
|
1 package gui.run;
2
3 import java.awt.Container;
4 import java.awt.FlowLayout;
5
6
7 public abstract class ThreadedRunButton extends
8 javax.swing.JButton implements
9 java.awt.event.ActionListener, Runnable {
10 public ThreadedRunButton(String label) {
11 this(label, null);
12 }
13
14 public ThreadedRunButton(String l, javax.swing.Icon i) {
15 super(l, i);
16 addActionListener(this);
17 }
18
19 public ThreadedRunButton(javax.swing.Icon i) {
20 this(null, i);
21 }
22
23 public ThreadedRunButton() {
24 this(null, null);
25 }
26
27 private Thread t = null;
28
29 /**
30 * interrupt the thread that the button started.
31 */
32 public void interrupt() {
33 t.interrupt();
34 }
35
36 public void actionPerformed(java.awt.event.ActionEvent e) {
37 t = new Thread(this);
38 t.start();
39 }
40
41
42 public static void main(String args[]) {
43 final ThreadedRunButton sleepingButton =
44 new ThreadedRunButton("sleep") {
45 public void run() {
46 try {
47 Thread.sleep(2000);
48 System.out.println("alarm!");
49 } catch (InterruptedException ie) {
50 System.out.println("You woke me up!");
51 }
52 }
53 };
54
55 gui.ClosableJFrame cf =
56 new gui.ClosableJFrame("Wake up!");
57 Container c = cf.getContentPane();
58 c.setLayout(new FlowLayout());
59 c.add(new ThreadedRunButton("wake the sleeper") {
60 public void run() {
61 sleepingButton.interrupt();
62 }
63 });
64 c.add(sleepingButton);
65 cf.setSize(200, 200);
66 cf.show();
67 }
68
69 }