Using Timer and JProgressBar

Last Modified On : Date Created: 01-dec-2000

/*
<applet  code=TimerApplet
    width=300 height=200>
</applet>
*/

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TimerApplet 
    extends JApplet
    implements ActionListener
{ 
   JTextField txtNo;  // take number
   JButton btnStart;  // to start count 

   // progress bar
   JProgressBar pb = new JProgressBar();

   int c,v;

    // timer to repeatedly perform action event
    Timer t;

    public void init()
    {
     JPanel tp = new JPanel();
     txtNo = new JTextField(10);

     btnStart = new JButton("Start");
     btnStart.addActionListener(this);
     tp.setLayout(new FlowLayout());

     // add components at top
     tp.add(new JLabel("Number"));
     tp.add(txtNo);
     tp.add(btnStart);



     // progress bar settings
     pb.setMinimum(1);
     pb.setBackground(Color.green);
     pb.setForeground(Color.red);
     pb.setStringPainted(true);

     Container c = getContentPane();
     c.add(tp,"North");
     c.add(pb, "South")
     
     // create a timer and set the interval to 500 milliseconds
     t  = new Timer(500,this);
 } // end of init

 public void actionPerformed(ActionEvent evt)
 {
  if ( evt.getSource() == btnStart)   // start button
  {
   // get value entered in textbox
   v = Integer.parseInt( txtNo.getText());

   // number is going to be maximum value of progressbar
   pb.setMaximum(v);
   c = 1;       // start counter
   t.start();  // timer starts

   // disable command button until counting is over
   btnStart.setEnabled(false);
 }
  else  // event by Timer 
  {
    pb.setValue(c);  // set value of progress bar
    c++;
    if ( c > v)  // if count > maximum number
    { 
      t.stop();   // stop timer
      btnStart.setEnabled(true);   // enable button
    } // end of inner if

  } // end of else
 
 } // end of actionperformed

} // end of applet