我正在尝试制作一个在单击按钮后执行某些任务的红绿灯。这个红绿灯应该做的是在 50 秒后从绿色变为黄色,在 10 秒后从黄色变为红色,在 60 秒后从红色变为绿色(这部分我工作正常),如果按下按钮时它是绿色的,它应该变成黄色,这应该只在绿色时至少经过 10 秒后才起作用。我有一个问题是如何检查 10 秒是否已经过去?
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();
}
}
}