1 8 9 package foxtrot.examples; 10 11 import java.awt.Container ; 12 import java.awt.GridBagLayout ; 13 import java.awt.Dimension ; 14 import java.awt.Toolkit ; 15 import java.awt.event.ActionListener ; 16 import java.awt.event.ActionEvent ; 17 import java.util.ArrayList ; 18 19 import javax.swing.JFrame ; 20 import javax.swing.JButton ; 21 22 import foxtrot.Task; 23 import foxtrot.Worker; 24 25 34 public class InterruptExample extends JFrame 35 { 36 private JButton button; 37 private boolean running; 38 private boolean taskInterrupted; 39 40 public static void main(String [] args) 41 { 42 InterruptExample example = new InterruptExample(); 43 example.setVisible(true); 44 } 45 46 public InterruptExample() 47 { 48 super("Foxtrot Example"); 49 50 final String label = "Run Task !"; 51 button = new JButton (label); 52 button.addActionListener(new ActionListener () 53 { 54 public void actionPerformed(ActionEvent e) 55 { 56 onButtonClick(label); 57 } 58 }); 59 60 setDefaultCloseOperation(EXIT_ON_CLOSE); 61 62 Container c = getContentPane(); 63 c.setLayout(new GridBagLayout ()); 64 c.add(button); 65 66 setSize(300, 200); 67 68 Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); 69 Dimension size = getSize(); 70 int x = (screen.width - size.width) >> 1; 71 int y = (screen.height - size.height) >> 1; 72 setLocation(x, y); 73 } 74 75 private void onButtonClick(final String label) 76 { 77 if (!running) 78 { 79 running = true; 80 81 button.setText("Interrupt"); 84 85 try 86 { 87 ArrayList list = getData(); 89 90 if (list == null) 93 { 94 return; 96 } 97 else 98 { 99 javax.swing.DefaultComboBoxModel model = new javax.swing.DefaultComboBoxModel (list.toArray()); 102 } 104 } 105 catch (Exception x) 106 { 107 x.printStackTrace(); 109 } 110 finally 111 { 112 button.setText(label); 114 115 setTaskInterrupted(false); 117 118 running = false; 120 } 121 } 122 else 123 { 124 126 button.setText(label); 128 129 setTaskInterrupted(true); 131 } 132 } 133 134 private ArrayList getData() throws Exception 135 { 136 return (ArrayList )Worker.post(new Task() 137 { 138 public Object run() throws Exception 139 { 140 System.out.println("Task started..."); 141 142 ArrayList list = new ArrayList (); 143 144 for (int i = 0; i < 100; ++i) 147 { 148 System.out.println("Heavy Operation number " + (i + 1)); 149 150 Thread.sleep(250); 152 153 Object data = new Object (); 155 list.add(data); 156 157 System.out.println("Checking if task is interrupted..."); 158 if (isTaskInterrupted()) 159 { 160 System.out.println("Task interrupted !"); 161 break; 162 } 163 System.out.println("Task not interrupted, going on"); 164 } 165 166 if (isTaskInterrupted()) 167 { 168 list.clear(); 171 return null; 172 } 173 174 return list; 175 } 176 }); 177 } 178 179 private synchronized boolean isTaskInterrupted() 180 { 181 return taskInterrupted; 187 } 188 189 private synchronized void setTaskInterrupted(boolean value) 190 { 191 taskInterrupted = value; 194 } 195 } 196 | Popular Tags |