Threads: Timer
Next
Applet
import java.awt.*;
import java.awt.event.*; // for ActionListener
class Timer extends Thread
{
TextField out;
int i=0;
Timer (TextField out) { this.out = out; }
public void run()
{
while (true)
{
try
{
sleep(1000);
}
catch (Exception e) { }
out.setText(String.valueOf(i++));
}
}
}
public class SecTimer extends java.applet.Applet
implements ActionListener
{
TextField out;
Button begn, done, susp, cont;
Timer timer;
public void init()
{
setLayout(new BorderLayout());
add("Center", out = new TextField());
out.setEditable(false);
out.setBackground(new Color(200,200,255));
out.setFont(new Font("TimesRoman",Font.BOLD,48));
Panel p = new Panel();
p.setLayout(new GridLayout(1,4));
p.add(begn = new Button("Start"));
p.add(done = new Button("Stop"));
p.add(susp = new Button("Suspend"));
p.add(cont = new Button("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)
{
timer.stop();
timer = null;
}
else
if (event.getSource() == susp)
{
if (timer != null) timer.suspend();
}
else
if (event.getSource() == cont)
{
if (timer != null) timer.resume();
}
}
}