Advertisement
mnaufaldillah

TrafficLightPane Tugas 2

Oct 18th, 2020
516
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1.  
  2. /**
  3. * Class untuk menampilkan lampu lalu lintas
  4. */
  5.  
  6. import java.awt.*;
  7. import javax.swing.*;
  8. import java.awt.event.*;
  9. public class TrafficLightPane extends JPanel
  10. {
  11. int tick = 1;
  12. int duration = 60;
  13. int state = 0;
  14. SignalPane green = new SignalPane(Color.green);
  15. SignalPane yellow = new SignalPane(Color.yellow);
  16. SignalPane red = new SignalPane(Color.red);
  17. DigitPane timerDigit = new DigitPane();
  18.  
  19. public TrafficLightPane (int s)
  20. {
  21. duration = s;
  22. setLayout(new GridLayout(4, 1));
  23. green.turnOn(false);
  24. yellow.turnOn(false);
  25. red.turnOn(true);
  26. timerDigit.setValue(duration);
  27. add(red);
  28. add(yellow);
  29. add(green);
  30. add(timerDigit);
  31. Timer timer = new Timer(1000, new ActionListener() {
  32. public void actionPerformed(ActionEvent e)
  33. {
  34. int timeRemaining = duration - tick;
  35.  
  36. if (timeRemaining <= 0)
  37. {
  38. tick = 0;
  39. state++;
  40. changeSignalState(state);
  41. }
  42.  
  43. timerDigit.setValue(duration - tick);
  44. tick++;
  45. }
  46. });
  47. timer.setRepeats(true);
  48. timer.setCoalesce(true);
  49. timer.start();
  50. }
  51.  
  52. //function untuk mengubah integer menjadi boolean
  53. private boolean changeToBool(int state)
  54. {
  55. if (state % 3 > 0)
  56. {
  57. return false;
  58. }
  59. else
  60. {
  61. return true;
  62. }
  63. }
  64.  
  65. //function untuk satet (on/off) dari object Signal
  66. private void changeSignalState(int state)
  67. {
  68. green.turnOn(changeToBool(state + 2));
  69. yellow.turnOn(changeToBool(state + 1));
  70. red.turnOn(changeToBool(state));
  71. }
  72.  
  73. public void setDuration(int s)
  74. {
  75. duration = s;
  76. }
  77. }
  78.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement