Second Counter

                      Next      Java Source      Java Application Source      Home

// Count seconds
import java.awt.*;
import java.awt.event.*;   // for ActionListener
import javax.swing.*;
import java.applet.*;

class Timer extends Thread {
   JTextField out;
   int i=0;
   
   Timer (JTextField out) { this.out = out;   }
   
   public void run() {
      while (true) {
         try {  sleep(1000);  } catch (InterruptedException e) {  }
         out.setText(String.valueOf(i++));
      }
   }
}

class SecTimerFrame extends JFrame implements ActionListener {
   JTextField out;
   JButton begn, done, susp, cont;
   Timer timer = null;
   
   public SecTimerFrame () {
      setLayout(new BorderLayout());
      add("Center", out = new JTextField());
      out.setEditable(false);
      out.setBackground(new Color(200,200,255));
      out.setFont(new Font("TimesRoman",Font.BOLD,48));
      
      JPanel p = new JPanel();
      p.setLayout(new GridLayout(1,4));
      p.add(begn = new JButton("Start"));
      p.add(done = new JButton("Stop"));
      p.add(susp = new JButton("Suspend"));
      p.add(cont = new JButton("Resume"));
      add("South", p);
            
      begn.addActionListener(this);
      done.addActionListener(this);
      susp.addActionListener(this);
      cont.addActionListener(this);
   }
            
   public void actionPerformed (ActionEvent event) {
      if (event.getSource() == begn) {
         timer = new Timer(out);
         timer.start();
      } else if (event.getSource() == done) {
         if (timer != null) timer.stop();
         timer = null;
      } else if (event.getSource() == susp) {
         if (timer != null) timer.suspend();
      } else if (event.getSource() == cont) {
         if (timer != null) timer.resume();
      }
   }
}

public class SecTimer extends Applet {
   public void init () {
      SecTimerFrame sec = new SecTimerFrame();
      sec.setSize(400,120);
      sec.setVisible(true);
   }
}