1 8 9 package foxtrot.examples; 10 11 import java.awt.Container ; 12 import java.awt.Dimension ; 13 import java.awt.GridBagLayout ; 14 import java.awt.Toolkit ; 15 import java.awt.event.ActionEvent ; 16 import java.awt.event.ActionListener ; 17 18 import javax.swing.JButton ; 19 import javax.swing.JFrame ; 20 21 import foxtrot.Task; 22 import foxtrot.Worker; 23 24 35 public class SimpleExample extends JFrame 36 { 37 private boolean sleeping; 38 private JButton button; 39 40 public static void main(String [] args) 41 { 42 SimpleExample example = new SimpleExample(); 43 example.setVisible(true); 44 } 45 46 public SimpleExample() 47 { 48 super("Foxtrot Example"); 49 50 button = new JButton ("Take a nap !"); 51 button.addActionListener(new ActionListener () 52 { 53 public void actionPerformed(ActionEvent e) 54 { 55 if (sleeping) 56 wakeUp(); 57 else 58 sleep(); 59 } 60 }); 61 62 setDefaultCloseOperation(EXIT_ON_CLOSE); 63 64 Container c = getContentPane(); 65 c.setLayout(new GridBagLayout ()); 66 c.add(button); 67 68 setSize(300, 200); 69 70 Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); 71 Dimension size = getSize(); 72 int x = (screen.width - size.width) >> 1; 73 int y = (screen.height - size.height) >> 1; 74 setLocation(x, y); 75 } 76 77 private void sleep() 78 { 79 button.setText("Wake me up!"); 80 workerSleep(); 81 button.setText("Take a nap!"); 83 } 84 85 private void workerSleep() 86 { 87 try 88 { 89 Worker.post(new Task() 90 { 91 public Object run() throws InterruptedException 92 { 93 synchronized (SimpleExample.this) 94 { 95 sleeping = true; 96 SimpleExample.this.wait(); 97 sleeping = false; 98 } 99 return null; 100 } 101 }); 102 } 103 catch (InterruptedException x) 104 { 105 x.printStackTrace(); 106 } 107 catch (Exception x) 108 { 109 } 111 } 112 113 private void freezeSleep() 114 { 115 try 116 { 117 synchronized (this) 118 { 119 sleeping = true; 120 wait(); 121 sleeping = false; 122 } 123 } 124 catch (InterruptedException x) 125 { 126 x.printStackTrace(); 127 } 128 } 129 130 private void wakeUp() 131 { 132 synchronized (this) 133 { 134 notifyAll(); 135 } 136 } 137 } 138 | Popular Tags |