/**
* Kode untuk menampilkan gambaran utuh sebuah lampu lalu lintas
* Kode ini akan menentukan lampu mana yang akan menyala dan berapa lama lampu tersebut akan menyala
*/
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TrafficLightPane extends JPanel
{
int tick = 1;
int duration = 10;
int state = 0;
SignalPane green = new SignalPane(Color.green);
SignalPane yellow = new SignalPane(Color.yellow);
SignalPane red = new SignalPane(Color.red);
DigitPane timerDigit = new DigitPane();
public TrafficLightPane(int s)
{
duration = s;
setLayout(new GridLayout(4,1));
green.turnOn(false);
yellow.turnOn(false);
red.turnOn(true);
timerDigit.setValue(duration);
add(red);
add(yellow);
add(green);
add(timerDigit);
Timer timer = new Timer(1000, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int timeRemaining = duration - tick;
if (timeRemaining <= 0)
{
tick = 0;
state++;
changeSignalState(state);
}
timerDigit.setValue(duration - tick);
tick++;
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
}
private boolean changeToBool(int state){
if (state % 3 > 0 )
{
return false;
}
else
{
return true;
}
}
private void changeSignalState(int state)
{
green.turnOn(changeToBool(state + 2));
yellow.turnOn(changeToBool(state + 1));
red.turnOn(changeToBool(state));
}
public void setDuration(int s)
{
duration = s;
}
}