/**
* Class untuk menampilkan traffic light
*/
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TrafficLightPane extends JPanel {
int tick = 1;
int duration = 60;
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();
}
//function u/ mengubah integer menjadi boolean
private boolean changeToBool(int state){
if (state % 3 > 0 ){
return false;
} else {
return true;
}
}
// function untuk mengubah state (on/off) dari object Signal
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;
}
}