My Java program is supposed to control a traffic light(an object created by another class) through means of JButton. Upon pressing a JButton, the traffic light is supposed to cycle from red to green, then yellow and back to red by calling on methods of the traffic light object.
The traffic light object has the methods .setGreen(); , .setYellow(); , .setRed(); and .wait(int milliseconds); and is visually displayed through a JFrame. By default it is set to red upon initiation. The program works just fine if I try to cycle the traffic light through means other than a JButton. For example, when using a for loop, the expected result is produced. My current approach is to have the JButton call on a cycle method that hands over the traffic light object to the cycle method. Within this method, the traffic light cycle should be realised. However, there seems to be a limit to the amount of actions this method can correctly perform. If the cycle method consists of only two instructions, for example .wait(1000); and .setGreen(); , the expected output is correctly produced. Upon packing more instructions to this method, it doesnt work as expected anymore.
final JButton button_cycle = new JButton("Begin cycle");
frame.add(button_cycle);
ActionListener alcycle= new ActionListener() {
@Override public void actionPerformed( ActionEvent button_cycle) {
{
cycle(myLight);
}
}
};
button_cycle.addActionListener(alcycle);
public static void cycle(TrafficLight myLight) {
myLight.wait(1000);
myLight.setGreen();
myLight.wait(1000);
myLight.setYellow();
myLight.wait(1000);
myLight.setRed();
}
The expected result upon pressing the button is the traffic light (red on default) to wait 1 second, switch to green, wait 1 more second, switch to yellow, wait 1 more second and switch back to red. Running the program results in the visual traffic light in the JFrame to stay red for 3 seconds and only executing the last .set operation. If the last operation in the cycle method is changed to myLight.setYellow(); for example, the traffic light stays red for 3 seconds and then switches to yellow.