forked from chetannihith/Java-hacktoberfest23
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrafficLightSimulator.java
80 lines (67 loc) · 2.43 KB
/
TrafficLightSimulator.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TrafficLightSimulator extends JFrame {
private JRadioButton redButton, yellowButton, greenButton;
private ButtonGroup buttonGroup;
private JPanel lightPanel;
public TrafficLightSimulator() {
// Create the frame
super("Traffic Light Simulator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(200, 400);
setLayout(new BorderLayout());
// Create the radio buttons
redButton = new JRadioButton("Red");
yellowButton = new JRadioButton("Yellow");
greenButton = new JRadioButton("Green");
// Create a button group to ensure only one light is selected at a time
buttonGroup = new ButtonGroup();
buttonGroup.add(redButton);
buttonGroup.add(yellowButton);
buttonGroup.add(greenButton);
// Create the light panel
lightPanel = new JPanel();
lightPanel.setBackground(Color.LIGHT_GRAY);
// Add radio buttons to the frame
JPanel controlPanel = new JPanel();
controlPanel.add(redButton);
controlPanel.add(yellowButton);
controlPanel.add(greenButton);
// Add action listeners to the radio buttons
redButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
lightPanel.setBackground(Color.RED);
}
});
yellowButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
lightPanel.setBackground(Color.YELLOW);
}
});
greenButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
lightPanel.setBackground(Color.GREEN);
}
});
// Add components to the frame
add(controlPanel, BorderLayout.NORTH);
add(lightPanel, BorderLayout.CENTER);
// Set the initial state
redButton.setSelected(true);
// Display the frame
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TrafficLightSimulator();
}
});
}
}