Timers
Previous
Next
Applet
Java Source
Java Application Source
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
interface Off { public void off (); }
class Timer extends Thread implements Off {
Off guest = null;
int amount, number=100;
long time_at_start;
public Timer (float a, Off g) {
amount = (int)(a*10);
guest = g;
setPriority(7);
}
public String getTime () {
long time_at_end = System.currentTimeMillis();
return String.valueOf((double)(time_at_end - time_at_start)/1000.0);
}
public void off () { stop(); }
public void run () {
time_at_start = System.currentTimeMillis();
try { sleep(number*amount); } catch (Exception e) { }
if (guest != null) guest.off();
}
}
class Application extends Thread implements Off {
Timer timer;
TextArea text;
int i=0;
float time_amt;
public Application (TextArea t, Choice cb) {
text = t;
time_amt = (new Float(cb.getSelectedItem())).floatValue();
timer = new Timer(time_amt, this);
}
public void off () {
text.append("Application "+String.valueOf(this)+" sent stop signal\n");
stop();
}
public void run () {
text.append("----------\n");
text.append("Starting Application "+String.valueOf(this)+": 1 tick/second\n");
text.append("Starting Timer for "+time_amt+" seconds\n");
timer.start();
for (i=1 ; i < 5 ; i++) {
try {
sleep(1000);
text.append("Application: "+i+"\n");
}
catch (Exception e) { text.append(String.valueOf(e)); }
}
text.append("Application Ending - turning timer off\n");
text.append("Timer reports "+timer.getTime()+" seconds used\n");
timer.off();
}
}
public class TimerTest extends Applet implements ActionListener {
Button startbut, resetbut;
TextArea text;
Choice cb;
public void init () {
setLayout(new BorderLayout(10,10));
Panel p = new Panel();
p.setLayout(new BorderLayout());
p.add("North", new Label("Results"));
p.add("Center", text = new TextArea(10,20));
add("Center", p);
Panel q = new Panel();
q.setLayout(new GridLayout(1,4,10,10));
q.add(startbut = new Button("Start"));
q.add(resetbut = new Button("Reset"));
q.add(new Label("Timer (secs)", Label.RIGHT));
q.add(cb = new Choice());
cb.addItem("0.5");
cb.addItem("1.0");
cb.addItem("1.5");
cb.addItem("2.0");
cb.addItem("2.5");
cb.addItem("3.0");
cb.addItem("3.5");
cb.addItem("4.0");
cb.addItem("4.5");
cb.addItem("5.0");
add("South", q);
startbut.addActionListener(this);
resetbut.addActionListener(this);
}
public void actionPerformed (ActionEvent e) {
if (e.getSource() == startbut) run();
else if (e.getSource() == resetbut) text.setText("");
}
public void run () {
Application s = new Application(text, cb);
s.start();
}
}