Skip to content

Commit 91d8380

Browse files
authored
Merge pull request #86 from ShreyasAnish/main
Create TrafficLight.java
2 parents 9614a19 + 6cd486e commit 91d8380

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed

AWT/TrafficLight.java

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
import java.awt.*;
2+
import javax.swing.*;
3+
import java.awt.event.*;
4+
5+
class Signal extends JPanel{
6+
Color on;
7+
boolean change;
8+
Signal(Color color){
9+
on=color;
10+
change=false;
11+
}
12+
public void turnOn(boolean a){
13+
change=a;
14+
repaint();
15+
}
16+
public Dimension getPreferredSize(){
17+
int size=(50)*2;
18+
return new Dimension(size,size);
19+
}
20+
public void paintComponent(Graphics g){
21+
g.setColor(Color.black);
22+
g.fillRect(0,0,150,250);
23+
if(change){
24+
g.setColor(on);
25+
}
26+
else{
27+
g.setColor(Color.white);
28+
}
29+
g.fillOval(10,10,80,80);
30+
}
31+
}
32+
33+
public class TrafficLight extends JFrame implements ActionListener{
34+
JRadioButton buttonRed,buttonYellow,buttonGreen;
35+
Signal green=new Signal(Color.green);
36+
Signal yellow=new Signal(Color.yellow);
37+
Signal red=new Signal(Color.red);
38+
39+
public TrafficLight(){
40+
setLayout(new FlowLayout());
41+
buttonRed=new JRadioButton("Red");
42+
buttonYellow=new JRadioButton("Yellow");
43+
buttonGreen=new JRadioButton("Green");
44+
buttonRed.addActionListener(this);
45+
buttonYellow.addActionListener(this);
46+
buttonGreen.addActionListener(this);
47+
JPanel trafficPanel=new JPanel(new GridLayout(3,1));
48+
trafficPanel.add(red);
49+
trafficPanel.add(yellow);
50+
trafficPanel.add(green);
51+
JPanel lightPanel=new JPanel(new FlowLayout());
52+
lightPanel.add(buttonRed);
53+
lightPanel.add(buttonYellow);
54+
lightPanel.add(buttonGreen);
55+
add(trafficPanel);
56+
add(lightPanel);
57+
pack();
58+
setVisible(true);
59+
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
60+
}
61+
62+
public static void main(String args[]){
63+
new TrafficLight();
64+
}
65+
66+
public void actionPerformed(ActionEvent e){
67+
if(e.getSource()==buttonRed){
68+
green.turnOn(false);
69+
yellow.turnOn(false);
70+
red.turnOn(true);
71+
buttonYellow.setSelected(false);
72+
buttonGreen.setSelected(false);
73+
}
74+
else if(e.getSource()==buttonYellow){
75+
green.turnOn(false);
76+
yellow.turnOn(true);
77+
red.turnOn(false);
78+
buttonRed.setSelected(false);
79+
buttonGreen.setSelected(false);
80+
}
81+
else if(e.getSource()==buttonGreen){
82+
green.turnOn(true);
83+
yellow.turnOn(false);
84+
red.turnOn(false);
85+
buttonYellow.setSelected(false);
86+
buttonRed.setSelected(false);
87+
}
88+
}
89+
}

0 commit comments

Comments
 (0)