1// Aim: Program to perform GUI operations (Traffic Light Simulator).
2import javax.swing.*;
3import java.awt.*;
4import java.awt.event.ActionEvent;
5import java.awt.event.ActionListener;
6
7public class TrafficLightSimulator extends JFrame implements ActionListener {
8 private JRadioButton redButton;
9 private JRadioButton yellowButton;
10 private JRadioButton greenButton;
11 private JPanel lightPanel;
12
13 public TrafficLightSimulator() {
14 setTitle("Traffic Light Simulator");
15 setSize(300, 400);
16 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
17 setLayout(new BorderLayout());
18
19 // Create radio buttons
20 redButton = new JRadioButton("Red");
21 yellowButton = new JRadioButton("Yellow");
22 greenButton = new JRadioButton("Green");
23
24 // Group the radio buttons
25 ButtonGroup group = new ButtonGroup();
26 group.add(redButton);
27 group.add(yellowButton);
28 group.add(greenButton);
29
30 // Add action listeners
31 redButton.addActionListener(this);
32 yellowButton.addActionListener(this);
33 greenButton.addActionListener(this);
34
35 // Create a panel for the buttons
36 JPanel buttonPanel = new JPanel();
37 buttonPanel.setLayout(new GridLayout(3, 1));
38 buttonPanel.add(redButton);
39 buttonPanel.add(yellowButton);
40 buttonPanel.add(greenButton);
41
42 // Create a panel for the lights
43 lightPanel = new JPanel() {
44 @Override
45 protected void paintComponent(Graphics g) {
46 super.paintComponent(g);
47 g.setColor(Color.BLACK);
48 g.fillRect(100, 50, 100, 300);
49
50 if (redButton.isSelected()) {
51 g.setColor(Color.RED);
52 g.fillOval(125, 75, 50, 50);
53 } else {
54 g.setColor(Color.DARK_GRAY);
55 g.fillOval(125, 75, 50, 50);
56 }
57
58 if (yellowButton.isSelected()) {
59 g.setColor(Color.YELLOW);
60 g.fillOval(125, 175, 50, 50);
61 } else {
62 g.setColor(Color.DARK_GRAY);
63 g.fillOval(125, 175, 50, 50);
64 }
65
66 if (greenButton.isSelected()) {
67 g.setColor(Color.GREEN);
68 g.fillOval(125, 275, 50, 50);
69 } else {
70 g.setColor(Color.DARK_GRAY);
71 g.fillOval(125, 275, 50, 50);
72 }
73 }
74 };
75
76 add(buttonPanel, BorderLayout.WEST);
77 add(lightPanel, BorderLayout.CENTER);
78 }
79
80 public void actionPerformed(ActionEvent e) {
81 lightPanel.repaint();
82 }
83
84 public static void main(String[] args) {
85 SwingUtilities.invokeLater(() -> {
86 TrafficLightSimulator frame = new TrafficLightSimulator();
87 frame.setVisible(true);
88 });
89 }
90}