Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes


Java Programming Code Examples

Java > Threads Code Examples

Stop watch programme

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
Stop watch programme import java.awt.event.*; import java.awt.*; import javax.swing.*; public class Stopwatch extends JFrame implements ActionListener, Runnable { private long startTime; private final static java.text.SimpleDateFormat timerFormat = new java.text.SimpleDateFormat("mm : ss.SSS"); private final JButton startStopButton= new JButton("Start/stop"); private Thread updater; private boolean isRunning= false; private final Runnable displayUpdater= new Runnable() { public void run() { displayElapsedTime(System.currentTimeMillis() - Stopwatch.this.startTime); } }; public void actionPerformed(ActionEvent ae) { if(isRunning) { long elapsed= System.currentTimeMillis() - startTime; isRunning= false; try { updater.join(); // Wait for updater to finish } catch(InterruptedException ie) {} displayElapsedTime(elapsed); // Display the end-result } else { startTime= System.currentTimeMillis(); isRunning= true; updater= new Thread(this); updater.start(); } } private void displayElapsedTime(long elapsedTime) { startStopButton.setText(timerFormat.format(new java.util.Date(elapsedTime))); } public void run() { try { while(isRunning) { SwingUtilities.invokeAndWait(displayUpdater); Thread.sleep(50); } } catch(java.lang.reflect.InvocationTargetException ite) { ite.printStackTrace(System.err); // Should never happen! } catch(InterruptedException ie) {} // Ignore and return! } public Stopwatch() { startStopButton.addActionListener(this); getContentPane().add(startStopButton); setSize(100,50); setVisible(true); } public static void main(String[] arg) { new Stopwatch().addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } }