-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrafficLight.java
91 lines (73 loc) · 2.97 KB
/
TrafficLight.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
81
82
83
84
85
86
87
88
89
90
91
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TrafficLight extends JFrame implements ActionListener {
JPanel lightPanel;
JTextField messageField;
Color currentColor;
JRadioButton redRadioButton;
JRadioButton yellowRadioButton;
JRadioButton greenRadioButton;
public TrafficLight() {
setTitle("Traffic Light GUI");
setSize(300, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
currentColor = Color.RED;
lightPanel = new JPanel() {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(100, 50, 100, 300);
g.setColor(currentColor == Color.RED ? Color.RED : Color.GRAY);
g.fillOval(125, 75, 50, 50);
g.setColor(currentColor == Color.YELLOW ? Color.YELLOW : Color.GRAY);
g.fillOval(125, 175, 50, 50);
g.setColor(currentColor == Color.GREEN ? Color.GREEN : Color.GRAY);
g.fillOval(125, 275, 50, 50);
}
};
lightPanel.setPreferredSize(new Dimension(300, 400));
lightPanel.setBackground(Color.WHITE);
redRadioButton = new JRadioButton("Red");
yellowRadioButton = new JRadioButton("Yellow");
greenRadioButton = new JRadioButton("Green");
ButtonGroup group = new ButtonGroup();
group.add(redRadioButton);
group.add(yellowRadioButton);
group.add(greenRadioButton);
JPanel radioButtonPanel = new JPanel();
radioButtonPanel.add(redRadioButton);
radioButtonPanel.add(yellowRadioButton);
radioButtonPanel.add(greenRadioButton);
messageField = new JTextField();
messageField.setEditable(false);
messageField.setHorizontalAlignment(JTextField.CENTER);
redRadioButton.addActionListener(this);
yellowRadioButton.addActionListener(this);
greenRadioButton.addActionListener(this);
add(lightPanel, BorderLayout.CENTER);
add(radioButtonPanel, BorderLayout.SOUTH);
add(messageField, BorderLayout.NORTH);
setVisible(true);
}
public void changeColor(Color color, String message) {
currentColor = color;
messageField.setText(message);
lightPanel.repaint();
}
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
if (src == yellowRadioButton) {
changeColor(Color.YELLOW, "READY!");
} else if (src == greenRadioButton) {
changeColor(Color.GREEN, "GO!");
} else if (src == redRadioButton) {
changeColor(Color.RED, "STOP!");
}
}
public static void main(String[] args) {
new TrafficLight();
}
}