i trying make stoplight performs tasks after button clicked. stoplight supposed change green yellow after 50 secs, yellow red after 10 secs, , red green after 60 secs (this part have working fine), , if button pressed when green should change yellow, should work after 10 secs have @ least passed while green. have problem how 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(); } } }
you can set timer when press button 10 seconds. when time expires, change color yellow via callback. better dealing exceptions, because should exceptional circumstances.
see this thread on how set timer later.
edit
the poster wishes not use timers. 1 way store time when button pressed in variable, access variable , compare against current time within while loop of run
method.
Comments
Post a Comment