-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrafficLightSimulator.java
More file actions
64 lines (55 loc) · 2.06 KB
/
TrafficLightSimulator.java
File metadata and controls
64 lines (55 loc) · 2.06 KB
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
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TrafficLightSimulator extends JFrame implements ActionListener {
private JLabel messageLabel;
private JRadioButton redButton, yellowButton, greenButton;
private ButtonGroup buttonGroup;
public TrafficLightSimulator() {
setTitle("Traffic Light Simulator");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
// Message label setup
messageLabel = new JLabel("");
messageLabel.setFont(new Font("Arial", Font.BOLD, 18));
add(messageLabel);
// Radio buttons for traffic lights
redButton = new JRadioButton("Red");
yellowButton = new JRadioButton("Yellow");
greenButton = new JRadioButton("Green");
// Add ActionListeners to the buttons
redButton.addActionListener(this);
yellowButton.addActionListener(this);
greenButton.addActionListener(this);
// Button group to ensure only one button is selected
buttonGroup = new ButtonGroup();
buttonGroup.add(redButton);
buttonGroup.add(yellowButton);
buttonGroup.add(greenButton);
// Add buttons to the frame
add(redButton);
add(yellowButton);
add(greenButton);
}
@Override
public void actionPerformed(ActionEvent e) {
if (redButton.isSelected()) {
messageLabel.setText("Stop");
messageLabel.setForeground(Color.RED);
} else if (yellowButton.isSelected()) {
messageLabel.setText("Ready");
messageLabel.setForeground(Color.ORANGE);
} else if (greenButton.isSelected()) {
messageLabel.setText("Go");
messageLabel.setForeground(Color.GREEN);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
TrafficLightSimulator frame = new TrafficLightSimulator();
frame.setVisible(true);
});
}
}