I am trying to make a stoplight that performs certain tasks after a button is clicked. What this stoplight is supposed to do is change from green to yellow after 50 secs, from yellow to red after 10 secs, and from red to green after 60 secs (this part I have working fine), and if the button is pressed when it is green it should change to yellow, this should only work after 10 secs have at least passed while green. What I have a problem is how do I check if 10 secs have passed or not?
public class Stoplight extends Applet
{
Button cross;
public void init(){
cross = new Button("Cross");
add(cross);
StoplightCanvas stoplightCanvas = new StoplightCanvas(cross);
add(stoplightCanvas);
new StoplightThread(stoplightCanvas).start();
}
}
class StoplightCanvas extends Canvas implements ActionListener
{
int Xpos;
int Ypos;
int diameter;
Button cross;
int x = 1;
StoplightCanvas(Button cross)
{
this.cross = cross;
cross.addActionListener(this);
setSize(300, 600);
}
public void paint(Graphics g)
{
diameter = 70;
Xpos = 70;
Ypos = 50;
g.setColor(Color.BLUE);
g.fillRect(70, 50, 74, 220);
g.setColor(Color.WHITE);
if (x == 1)
g.setColor(Color.RED);
drawCircles(g, Xpos, Ypos);
g.setColor(Color.WHITE);
if (x == 2)
g.setColor(Color.YELLOW);
drawCircles(g, Xpos, Ypos + diameter);
g.setColor(Color.WHITE);
if (x == 3)
g.setColor(Color.GREEN);
drawCircles(g, Xpos, Ypos + diameter * 2);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == cross) {
}
repaint();
}
void drawCircles(Graphics g, int x, int y)
{
g.fillOval(x, y, diameter, diameter);
}
public void toggleColor() {
if (x == 1)
x = 3;
else if (x == 2)
x = 1;
else if (x == 3)
x = 2;
}
}
class StoplightThread extends Thread
{
StoplightCanvas stoplightCanvas;
StoplightThread(StoplightCanvas stoplightCanvas) {
this.stoplightCanvas = stoplightCanvas;
}
public void run()
{
while (true) {
try {
if (stoplightCanvas.x == 3){
Thread.sleep(50000);
} else if (stoplightCanvas.x == 2) {
Thread.sleep(10000);
} else if (stoplightCanvas.x == 1) {
Thread.sleep(60000);
}
} catch (InterruptedException e){}
stoplightCanvas.toggleColor();
stoplightCanvas.repaint();
}
}
}