|
| 1 | +/* |
| 2 | + * Create a programm to simulate Traffic Lights. The program lets the user |
| 3 | + * select one of three lights: red, yellow or Green with radio buttons. On |
| 4 | + * selecting radio button, an appropriate message with “stop” or “Ready” or “GO” |
| 5 | + * should appear above the button in selected color. Initially, there is no |
| 6 | + * message Shown. |
| 7 | + */ |
| 8 | + |
| 9 | +package Traffic_Lights; |
| 10 | + |
| 11 | +import javax.swing.*; |
| 12 | +import java.awt.*; |
| 13 | +import java.awt.event.*; |
| 14 | + |
| 15 | +class Lights extends JFrame implements ItemListener { |
| 16 | + public JLabel l1, l2; |
| 17 | + public JRadioButton r1, r2, r3; |
| 18 | + public ButtonGroup bg; |
| 19 | + public JPanel p, p1; |
| 20 | + |
| 21 | + public Lights() { |
| 22 | + setLayout(new GridLayout(2, 1)); |
| 23 | + setSize(800, 400); |
| 24 | + |
| 25 | + p = new JPanel(new FlowLayout()); |
| 26 | + p1 = new JPanel(new FlowLayout()); |
| 27 | + |
| 28 | + l1 = new JLabel(); |
| 29 | + Font f = new Font("Verdana", Font.BOLD, 80); |
| 30 | + l1.setFont(f); |
| 31 | + add(l1); |
| 32 | + p.add(l1); |
| 33 | + |
| 34 | + add(p); |
| 35 | + |
| 36 | + l2 = new JLabel("Select Lights"); |
| 37 | + p1.add(l2); |
| 38 | + |
| 39 | + JRadioButton r1 = new JRadioButton("Red Light"); |
| 40 | + r1.setBackground(Color.red); |
| 41 | + p1.add(r1); |
| 42 | + r1.addItemListener(this); |
| 43 | + |
| 44 | + JRadioButton r2 = new JRadioButton("Yellow Light"); |
| 45 | + r2.setBackground(Color.YELLOW); |
| 46 | + p1.add(r2); |
| 47 | + r2.addItemListener(this); |
| 48 | + |
| 49 | + JRadioButton r3 = new JRadioButton("Green Light"); |
| 50 | + r3.setBackground(Color.GREEN); |
| 51 | + p1.add(r3); |
| 52 | + r3.addItemListener(this); |
| 53 | + |
| 54 | + add(p1); |
| 55 | + |
| 56 | + bg = new ButtonGroup(); |
| 57 | + bg.add(r1); |
| 58 | + bg.add(r2); |
| 59 | + bg.add(r3); |
| 60 | + setVisible(true); |
| 61 | + } |
| 62 | + |
| 63 | + public void itemStateChanged(ItemEvent i) { |
| 64 | + JRadioButton jb = (JRadioButton) i.getSource(); |
| 65 | + switch (jb.getText()) { |
| 66 | + case "Red Light": { |
| 67 | + l1.setText("STOP"); |
| 68 | + l1.setForeground(Color.RED); |
| 69 | + } |
| 70 | + break; |
| 71 | + case "Yellow Light": { |
| 72 | + l1.setText("Ready"); |
| 73 | + l1.setForeground(Color.YELLOW); |
| 74 | + } |
| 75 | + break; |
| 76 | + case "Green Light": { |
| 77 | + l1.setText("GO"); |
| 78 | + l1.setForeground(Color.GREEN); |
| 79 | + } |
| 80 | + break; |
| 81 | + } |
| 82 | + } |
| 83 | +} |
| 84 | + |
| 85 | +public class traffic_lights { |
| 86 | + public static void main(String[] args){ |
| 87 | + new Lights(); |
| 88 | + } |
| 89 | +} |
0 commit comments