I've tried to change to yellow, then pause for 4 seconds before changing to green but it doesn't work.

public TrafficLight()
    {
        // Construct the circles
        red = new Circle();
        yellow = new Circle();
        green = new Circle();




// Set their color and make them visible


    red.changeColor("red");
    red.makeVisible();
    red.moveHorizontal(200);
    red.moveVertical(200);
    yellow.changeColor("black");
    yellow.makeVisible();
    yellow.moveHorizontal(200);
    yellow.moveVertical(250);
    green.changeColor("black");
    green.makeVisible();
    green.moveHorizontal(200);
    green.moveVertical(300);
    // Set stop to be true;
    stop = true;

}

 public void change() {

    TrafficLight t1 = new TrafficLight();
    if (stop = true) {
        green.changeColor("green");           
    }
    else {
        yellow.changeColor("yellow");

}


}

This is where i'm having the problem.

Also, this is the code for making the yellow light pause for 4 seconds but it's not working.

private void pause() {

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
        }
    }
}

Recommended Answers

All 2 Replies

Line 34 you are assigning the value of true to the variable stop. The test for equals is ==

You may also be blocking the Swing event dispatch thread depending on what the restof your code looks like. Everything to do with Swing (eg painting the screen, running actionPerformed methods) happens on a single thread - the "Event Dispatch Thread", or "EDT", or "Swing thread".
That means that once your actionPerformed method starts NOTHING else will happen in Swing, including no screen updates, until your method finishes. You can update stuff and loop and sleep as much as you like, but none of that will affect what's on the screen until your method has terminated.
If you want to do stuff in steps over a period of time the this is the right way:
In your actionPerformed start a javax.swing.Timer, and return. Every time the timer fires you can update whatever needs updating and return. Inbetween the timer firings Swing will be free to update the screen.

Thanks, I'll try that.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.